Nest
中间件 middleware
NestMiddleware 中间件的实现与注册
中间件 Middleware
完全可以按照
Express中的中间件去理解它,主要就是为了处理一些基础性的问题,比如通用日志、跨域、给请求头增加参数等等。中间件模块必须要实现
NestMiddleware接口。
自定义中间件的开发
// logger.middleware.ts
import { NestMiddleware, Injectable } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
req.headers['user-id'] = 'xxx' // 后续在 请求中使用 @Req 参数即可获得这个 user-id
console.log('request...')
next();
}
}
/**
* 实际上这种没有任何状态的中间件完全可以通过函数去声明,并且使用
*/
export function logger(req: Request, res: Response, next: NextFunction) {
console.log('function request...')
next();
}自定义中间件的使用
使用时有两种,一种是全局一种不是(实际上也可以称之为全局可控性比较强),全局指在入口文件中通过 app.use 注册的中间件。此种方案无法支持依赖注入,同时也仅支持函数式中间件的使用
// main.ts
const app = await NestFactory.create(AppModule);
app.use(logger);在 app.module.ts 中去使用这个组件间则必须要实现 NestModule 接口。
import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { LoggerMiddleware } from './middlewares/logger.middleware.ts';
@Module({})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.exclude(
{ route: '/users', method: RequestMethod.GET },
'messages/*'
)
.forRoutes(CatsController)
}
}apply使用中间件的方法,多个可以是apply(cors(), LoggerMiddleware)exclude不是必须的,可以指定排除的路由,也就是这些路由不会在这个中间件中生效;可以是对象,也可以是路由通配符。forRoutes可以是对应的controller也可以是通配符,比如*标识所有