中间件的学习

编程入门 行业动态 更新时间:2024-10-10 06:13:42

<a href=https://www.elefans.com/category/jswz/34/1771157.html style=中间件的学习"/>

中间件的学习

中间件是在路由处理程序之前调用的函数。中间件函数可以访问请求和相应对象,以及应用程序请求-响应周期中的中间件函数。

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)

更多推荐

中间件的学习

本文发布于:2024-03-23 21:23:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1742986.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!