中间件就是匹配路由以前或者匹配路由完成作的一系列的操做。中间件中若是想往下 匹配的话,那么须要写 next()
。express
Nestjs 的中间件实际上等价于 express 中间件。 下面是 Express 官方文档中所述的中间件功能:markdown
中间件函数能够执行如下任务:app
执行任何代码。
对请求和响应对象进行更改。
结束请求-响应周期。
调用堆栈中的下一个中间件函数。
若是当前的中间件函数没有结束请求-响应周期, 它必须调用 next() 将控制传递给下一个中间 件函数。不然, 请求将被挂起。
复制代码
Nest 中间件能够是一个函数,也能够是一个带有@Injectable()
装饰器的类。cors
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();
} }
复制代码
在 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);
复制代码