如何在NestJS中针对不同请求方法配置指定中间件?
解决NestJS中间件作用范围配置问题
嘿,这个问题很好搞定!你只需要把两个中间件的配置拆分开,分别指定它们的生效规则就行啦。原来的代码把两个中间件绑定到了同一条路由规则上,所以它们会对所有请求方法生效。现在我们分开配置就能实现需求:
import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common'; import { AuthenticationMiddleware } from './path-to-authentication-middleware'; import { RequestFilterMiddleware } from './path-to-request-filter-middleware'; export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { // 让AuthenticationMiddleware保持对所有请求方法生效 consumer .apply(AuthenticationMiddleware) .forRoutes({ path: '/**', method: RequestMethod.ALL }); // 单独配置RequestFilterMiddleware,仅对GET请求生效 consumer .apply(RequestFilterMiddleware) .forRoutes({ path: '/**', method: RequestMethod.GET }); } }
简单解释下逻辑
NestJS的MiddlewareConsumer支持多次调用apply()和forRoutes()方法,这样我们就能为每个中间件单独定义作用的路由范围和请求方法。通过拆分配置后:
AuthenticationMiddleware依然覆盖所有路径、所有请求方法RequestFilterMiddleware只会作用于所有路径下的GET请求
如果之后需要调整特定路径的规则,直接修改对应forRoutes里的path参数就可以啦。
内容的提问来源于stack exchange,提问作者Vignesh
相关产品推荐
相关产品推荐

