中间件
又名为消费者, 中间层
原理
- 客户端 -> 中间件 -> 路由
- 客户端发送
HTTP到达路由之前经过中间件处理 - 类似于
express的中间件, 使用next(), 客户端发送HTTP先经过这个中间件处理,之后在next下一步到达路由
使用
- 创建
file.middleware.ts文件 - 使用
@Injectable装饰 - 需要实现中间件类型(class)
implements NestMiddleware - 使用关键字
use定义中间件 - 使用
next到达下一个路由 - 中间件在
app.module中使用 app.module需要继承NestModule- 使用关键字
configure配置中间件 - 使用关键字
apply()参数为定义的中间件, 例如loggerMiddleware - 使用
forRoutes配置需要处理路由
- forRoutes()
- 参数为字符串时: 路由路径, 不带
/ - 参数为控制器时: 与字符串处理相同, 处理控制器的路由, 例如
CatController - 参数为对象时:
- path 路由路径, 不带
/ - method 处理请求方法的某一个
- GET: RequestMethod.GET, 从
@nestjs/common导入 - ALL: RequestMethod.ALL
- GET: RequestMethod.GET, 从
可选链: exclued() 排除路由 inclued()
forRoutes例子
configure (consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes({
path: 'cat',
method: RequestMethod.GET,
})
}