nestjs 开发过程中可能会碰到一些需要通过监听用户行为等功能,那么可能就会用到了中间件功能了,例如:我们建立一个日志监听用户访问接口频率,监听用户访问接口的版本等
中间件是在路由处理程序 之前 调用的函数。 中间件函数可以访问请求和响应对象,以及应用程序请求响应周期中的 next()中间件函数。next() 中间件函数通常由名为 next 的变量表示

Nest 中间件实际上等价于 express 中间件
中间件函数可以执行以下任务:
- 执行任何代码。
- 对请求和响应对象进行更改。
- 结束请求-响应周期。
- 调用堆栈中的下一个中间件函数。
- 如果当前的中间件函数没有结束请求-响应周期, 它必须调用
next()将控制传递给下一个中间件函数。否则, 请求将被挂起。
您可以在函数中或在具有 @Injectable() 装饰器的类中实现自定义 Nest中间件。 这个类应该实现 NestMiddleware 接口, 而函数没有任何特殊的要求
js
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class AppMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
//可以在这里处理我们想处理的任务,需要住一定的是别忘了next的执行
next();
}
}
中间件不能在 @Module() 装饰器中列出。我们必须使用模块类的 configure() 方法来设置它们。包含中间件的模块必须实现 NestModule 接口。我们将 AppMiddleware 设置在 ApplicationModule 层上,即: AppModule
ps:一般根据自己需求放在所属,我这里假设是一个全局的日志监听,就放到 app 中,就自然到 appmodule 中了
js
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppMiddleware } from './app.middleware';
import { UserController } from './user/user.controller';
import { ArticleController } from './article/article.controller';
@Module({
imports: [],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AppMiddleware)
.forRoutes('user', 'article') //支持字符串
.forRoutes({ path: 'user', method: RequestMethod.GET }) //支持请求类型
.forRoutes({ path: 'u*r', method: RequestMethod.ALL }) //支持通配符
.forRoutes('*') //通配符所有请求
.forRoutes(UserController, , ArticleController) //支持直接传递类
.exclude(
{ path: 'user', method: RequestMethod.GET }, //支持过滤排除
{ path: 'user', method: RequestMethod.POST },
'user/(.*)',
)
}
}
这样就可以实现中间件监听网络请求了