中間件就是匹配路由以前或者匹配路由完成作的一系列的操做。中間件中若是想往下 匹配的話,那麼須要寫 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);
複製代碼