中间件的学习"/>
中间件的学习
中间件是在路由处理程序之前调用的函数。中间件函数可以访问请求和相应对象,以及应用程序请求-响应周期中的中间件函数。
1.编写中间件
中间件包含三个参数:req,res,next next为放行函数,不执行next()语句,需执行该中间件的路由会被挂起。
#logger.middleware.ts
import { NestMiddleware, Injectable } from "@nestjs/common";
import { Request, Response, NextFunction } from "express";@Injectable()
export class LoggerMiddleware implements NestMiddleware {use(req: Request, res: Response, next: NextFunction) {next()console.log(req.method + ' ' + req.url + ' ' + res.statusCode);}
}
2.应用中间件
在app模块中注入中间件
#app.module.ts
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';@Module({imports: [ CatsModule],controllers: [AppController],providers: [AppService],
})
export class AppModule implements NestModule {configure(consumer: MiddlewareConsumer) {consumer.apply(LoggerMiddleware) //运用中间件.forRoutes('cats'); //cats模块的路由将会经过中间件函数}
}
2.1匹配路由
匹配规定的路由,可使用正则
#app.module
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common'; consumer.apply(LoggerMiddleware).forRoutes({ path: 'cats/*', method: RequestMethod.GET }, //匹配cats下所有get请求路由{ path: 'cats', method: RequestMethod.POST} //匹配cats的post请求
);
2.2去除路由
不想要某些模块的路由经过中间件 使用exclude
#app.module.tsconsumer.apply(LoggerMiddleware).exclude({ path: 'cats', method: RequestMethod.GET },//不经过cats的get请求 /cats/1 仍会经过{ path: 'cats', method: RequestMethod.POST }, // 'cats/(.*)', //放开将不会经过cats下所有的路由).forRoutes(CatsController);
2.3路由通配符
forRoutes({ path: 'ab*cd', method: RequestMethod.ALL }); //将匹配路由以ab开头,cd结尾的路由
3.功能性中间件
我们也可以使用简单的函数来定义中间件,它比类更加简单,用法与类一致。
# function.middleware.ts
import { Request, Response, NextFunction } from "express";export function logger(req: Request, res: Response, next: NextFunction) {console.log("Requested URL:", req.url);next();
}
# app.module.tsimport { logger } from './middleware/function.middleware';
...consumer.apply(logger).forRoutes(CatsController) //功能中间件
4.多个中间件
绑定多个中间件,中间使用逗号隔开
# app.module.ts
//多个中间件consumer.apply(testLogger,LoggerMiddleware,logger).forRoutes(CatsController)
5.全局中间件
挂载全局注册
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);
ps:附上官网链接 中间件 |NestJS 中文文档 |NestJS 中文网 (bootcss)
更多推荐
中间件的学习
发布评论