基本
中间件是在路由处理程序 之前 调用的函数。 中间件函数可以访问请求和响应对象,以及应用程序请求响应周期中的 next() 中间件函数。 next() 中间件函数通常由名为 next 的变量表示。
基本使用
官方的一个例子,使用@Injectable()实现自定义 Nest中间件。 这个类应该实现 NestMiddleware 接口, 而函数没有任何特殊的要求。
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log('Request...');
next();
}
}
应用中间件
中间件不能在 @Module() 装饰器中列出。我们必须使用模块类的 configure() 方法来设置它们。我们需要一个NestModule的接口去约束一个类。实现 configure 返回一个消费者 consumer 通过 apply 注册中间件 通过forRoutes 指定 Controller 路由。
我们也可以指定一个Controller去使用中间件
forRoutes(自定义Controller)这样的形式去使用。
[当然还有别的使用方法](中间件 (nestjs.cn))
对接口类型进行中间件拦截
consumer
.apply(LoggerMiddleware)
.exclude(
{ path: 'cats', method: RequestMethod.GET },
{ path: 'cats', method: RequestMethod.POST },
'cats/(.*)',
)
.forRoutes(CatsController);
函数式使用
以函数的方式去定义一个中间件
多个中间件
为了绑定顺序执行的多个中间件,我们可以在 apply() 方法内用逗号分隔它们。
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
全局使用
如果我们想一次性将中间件绑定到每个注册路由,我们可以使用由INestApplication实例提供的 use()方法:
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);