nestjs中间件简介

nestjs 开发过程中可能会碰到一些需要通过监听用户行为等功能,那么可能就会用到了中间件功能了,例如:我们建立一个日志监听用户访问接口频率,监听用户访问接口的版本等

中间件简介

中间件是在路由处理程序 之前 调用的函数。 中间件函数可以访问请求和响应对象,以及应用程序请求响应周期中的 next()中间件函数。next() 中间件函数通常由名为 next 的变量表示

Nest 中间件实际上等价于 express 中间件

中间件函数可以执行以下任务:

  • 执行任何代码。
  • 对请求和响应对象进行更改。
  • 结束请求-响应周期。
  • 调用堆栈中的下一个中间件函数。
  • 如果当前的中间件函数没有结束请求-响应周期, 它必须调用 next() 将控制传递给下一个中间件函数。否则, 请求将被挂起。

您可以在函数中或在具有 @Injectable() 装饰器的类中实现自定义 Nest中间件。 这个类应该实现 NestMiddleware 接口, 而函数没有任何特殊的要求

js 复制代码
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class AppMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    //可以在这里处理我们想处理的任务,需要住一定的是别忘了next的执行
    next();
  }
}

中间件不能在 @Module() 装饰器中列出。我们必须使用模块类的 configure() 方法来设置它们。包含中间件的模块必须实现 NestModule 接口。我们将 AppMiddleware 设置在 ApplicationModule 层上,即: AppModule

ps:一般根据自己需求放在所属,我这里假设是一个全局的日志监听,就放到 app 中,就自然到 appmodule 中了

js 复制代码
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppMiddleware } from './app.middleware';
import { UserController } from './user/user.controller';
import { ArticleController } from './article/article.controller';

@Module({
  imports: [],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AppMiddleware)
      .forRoutes('user', 'article') //支持字符串
      .forRoutes({ path: 'user', method: RequestMethod.GET }) //支持请求类型
      .forRoutes({ path: 'u*r', method: RequestMethod.ALL }) //支持通配符
      .forRoutes('*') //通配符所有请求
      .forRoutes(UserController, , ArticleController) //支持直接传递类
      .exclude(
        { path: 'user', method: RequestMethod.GET }, //支持过滤排除
        { path: 'user', method: RequestMethod.POST },
        'user/(.*)',
      )
  }
}

这样就可以实现中间件监听网络请求了

相关推荐
HxY7 天前
Server Sent Event 技术实践
前端·后端·nestjs
浪遏19 天前
大文件上传👈 | React + NestJs |分片、断点续传、秒传🚀 , 你是否知道 ???
前端·面试·nestjs
白日梦想家12261 个月前
【nest系列】之 VO 的配置
nestjs
Junior_FE_20221 个月前
gRPC在Nest中的尝试
后端·nestjs
UOrb1 个月前
手把手从零到一打造在线文档之后端项目搭建
前端·nestjs
东方小月1 个月前
NestJS中如何优雅的实现接口日志记录
前端·后端·nestjs
Running_slave2 个月前
搭建Nestjs+TypeORM+TS服务端应用架构
前端·后端·nestjs
东方小月2 个月前
如何使用GitHub Actions自动部署我们的项目
前端·github·nestjs
泰伦闲鱼2 个月前
nestjs:GET REQUEST 缓存问题
服务器·前端·缓存·node.js·nestjs
求知若饥2 个月前
NestJS 项目实战-权限管理系统开发(六)
后端·node.js·nestjs