Nestjs的中间件实际上等价于 express 中间件。 下面是Express官方文档中所述的中间件功能: 中间件函数可以执行以下任务:
执行任何代码。 对请求和响应对象进行更改。 结束请求-响应周期。 调用堆栈中的下一个中间件函数。 如果当前的中间件函数没有结束请求-响应周期, 它必须调用 next() 将控制传递给下一个中间件函数。否则, 请求将被挂起。
Nest 中间件可以是一个函数,也可以是一个带有 @Injectable() 装饰器的类
1、创建中间件
nest g middleware init
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class InitMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.log('init');
next();
}
}
2、配置Nestjs中间件
在app.module.ts中继承NestModule然后配置中间件
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(InitMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL })
.apply(NewsMiddleware)
.forRoutes({ path: 'news', method: RequestMethod.ALL })
.apply(UserMiddleware).
forRoutes({ path: 'user', method: RequestMethod.GET },{ path: '', method: RequestMethod.GET });
}
}
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
export function logger(req, res, next) {
console.log(`Request...`);
next();
};
const app = await NestFactory.create(ApplicationModule); app.use(logger); await app.listen(3000);