希曼日记

Middleware

中间件

又名为消费者,中间层

原理

  • 客户端 -> 中间件 -> 路由
  • 客户端发送HTTP到达路由之前经过中间件处理
  • 类似于express的中间件,使用next(),客户端发送HTTP先经过这个中间件处理,之后在next下一步到达路由

使用

  1. 创建file.middleware.ts文件
  2. 使用@Injectable装饰
  3. 需要实现中间件类型(class)implements NestMiddleware
  4. 使用关键字use定义中间件
  5. 使用next到达下一个路由
  6. 中间件在app.module中使用
  7. app.module需要继承NestModule
  8. 使用关键字configure配置中间件
  9. 使用关键字apply() 参数为定义的中间件,例如loggerMiddleware
  10. 使用forRoutes配置需要处理路由
  • forRoutes()
  • 参数为字符串时:路由路径,不带/
  • 参数为控制器时:与字符串处理相同,处理控制器的路由,例如CatController
  • 参数为对象时:
  • path 路由路径,不带/
  • method 处理请求方法的某一个
    • GET: RequestMethod.GET,从@nestjs/common导入
    • ALL: RequestMethod.ALL

可选链: exclued() 排除路由 inclued()

  1. forRoutes例子
JavaScript
configure (consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes({
path: 'cat',
method: RequestMethod.GET,
})
}