nodejs企业级开发框架nest学习总结 - 2.NestJS入门middleware、exceptionFilter、Pipe。
发布时间:2026/7/28 14:03:12
分类:文化教育
浏览:1234

NestJS入门middleware、exceptionFilter、pipe。前面一节介绍了NestJS的controller、DTO、providers、module等的学习1.middleware中间件是在路由处理程序之前调用的函数。中间件函数可以访问请求和响应对象,以及next()应用程序请求 - 响应周期中的中间件功能。中间件例子:core跨域中间件、bodyparser中间件、jwt中间件、logger日志中间件等等等官方实例日志中间件,小改动1.1中间件类,实现NestMiddleware接口,重写use方法// middleware/logger.middleware.tsimport{Injectable,NestMiddleware}from'@nestjs/common';import{Request,Response}from'express';/** * * 依赖注入 * Nest中间件完全支持依赖注入。与提供者和控制器一样,他们能够注入同一模块中可用的依赖项。像往常一样,这是通过constructor。 * @Injectable 1.注册成nest知道的提供者可以注入的 */@Injectable()exportclassLoggerMiddlewareimplementsNestMiddleware{// 继承NestMiddleware 实现中间件publicuse(req:Request,res:Response,next:(url?:string)=void){console.log('logger...');next();// 记得要next,让中间件过滤后通过}}1.2 方法中间件// middleware/logger.middleware.ts 补充下面代码import{Request,Response,NextFunction}from'express';/** * @Param 2.功能中间件 在您的中间件不需要任何依赖项时,请考虑使用更简单的功能中间件替代方案。 */exportfunctionlogger(req:Request,res:Response,next:NextFunction){console.log('logger...');next();}1.3 中间件的使用,先配置中间件import{Module,NestModule,MiddlewareConsumer,RequestMethod}from'@nestjs/common';import{AppController}from'./app.controller';import{AppService}from'./app.service';import{LoggerMiddleware,logger}from'./middleware/logger.middleware';@Module({controllers:[AppController],// 在此模块中定义的控制器集,必须进行实例化providers:[AppService],// 注册服务成一个提供者,提供给controller使用exports:[AppService],// 我们想要共享AppService服务的实例给其它模块使用,为了做到这一点,我们需要导出providers里面的服务,提供给其他模块使用。(导出proivders里面的服务,给其他模块使用)})exportclassChildModuleimplementsNestModule{// 实现NestModule接口,从而配置中间件// MiddlewareConsumer是一个帮助类。它提供了几种内置方法来管理中间件publicconfigure(consumer:MiddlewareConsumer){// 1.应用中间件,注册LoggerMiddleware中间件到那些路由中 * 表示任意路由consumer// 为了绑定顺序执行的多个中间件,只需在apply()方法中提供逗号分隔的列表:.apply(LoggerMiddleware,logger)// apply()方法可以采用单个中间件,也可以使用(多个参数来指定多个中间件。)// 4.1 排除某些路由使用中间件.exclude({path:'user',method:RequestMethod.GET},// { path: 'user', method: RequestMethod.POST },).forRoutes('*');// 2.或者选择路由路径+请求的方式 post请求 才会通过中间件// 3. .forRoutes({ path: 'user', method: RequestMethod.POST });// 4. .forRoutes(AppController) 放入一个controller,控制整个路由都要通过中间件}}配置中间件middleware,需要实现Nest提供的NestModule接口,重写configure方法重写的configure参数为MiddlewareConsumer类型的一个参数,用于配置中间件consumer.apple(...arg)// 使用中间件,接收一个0-n个参数,参数为每一个中间件,并且顺序执行的多个中间件.exclude({path:'user',method:RequestMethod.ALL},)// 接收0-n个排除的对象,排除哪个路由,那种请求方式不需要使用中间件// path: 'user', method: RequestMethod.ALL表示除了/user里面的全部请求方式之外的全部路由都使用中间件.forRoutes('*');//表示应用了全局的路由,除了exclude之外// .forRoutes('/user/*');表示应用于/user/*的路由// forRoutes里面也可以接受一个和exclude需要的对象一致的参数,也可以直接放入一个控制器RequestMethod.ALL,GET,POST,DELETE.PATCH,PUT...全局使用中间件constapp=awaitNestFactory.create(AppModule);app.use(loggerMiddleware,logger);awaitapp.listen(3000);2.异常类自带异常类:HttpException,相当于把相同默认异常返回的数据重写(内置HttpException类从@nestjs/common包中暴露出来。)@Get()asyncfindAll(){//接收两个参数,第一个是string | object类型,第二个参数是接收返回的statusCode码thrownewHttpException('This is a custom message',HttpStatus.FORBIDDEN);/* throw new HttpException({ status: HttpStatus.FORBIDDEN, //status状态码 error: 'This is a custom message', //错误信息 }, HttpStatus.FORBIDDEN); */}抛出异常,异常信息: HttpStatus.FORBIDDEN:就是403{"statusCode":