[英]Nest.js - skip middleware based on header value
I have an application which uses nestjs
and MiddlewareConsumer
.我有一个使用
nestjs
和MiddlewareConsumer
的应用程序。 I would like to know if there's a way to skip a middleware based on a header value?我想知道是否有办法跳过基于 header 值的中间件?
I checked documentation and saw that I can only use path or method (as I do now) but maybe there's something I'm missing?我检查了文档,发现我只能使用路径或方法(就像我现在所做的那样),但也许我缺少一些东西?
Sample of my code:我的代码示例:
export class AuthorizationModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(DiscriminatorValidator).with(common.USERS).forRoutes(
{path: RELATIVE_RESOURCE_PATH, method: RequestMethod.POST},{path: RELATIVE_RESOURCE_PATH, method: RequestMethod.PUT});
consumer.apply(validate).forRoutes(AuthorizationController);
consumer.apply(HeadersValidator).with().forRoutes(AuthorizationController);
consumer.apply(ContextAndHeadersMiddleware).forRoutes(AuthorizationController);
}
}
This is not possible with the MiddlewareConsumer
.这对于
MiddlewareConsumer
是不可能的。
However, the middleware itself can check if its applicable or should be skipped:但是,中间件本身可以检查它是否适用或应该被跳过:
@Injectable()
export class ContextAndHeadersMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
if (req.get('my-header') === 'SKIP') {
// skip this middleware if header value is set
return next();
}
// middleware logic
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.