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/(.*)',
      )
  }
}

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

相关推荐
onebyte8bits3 小时前
NestJS 系列教程(十八):文件上传与对象存储架构(Multer + S3/OSS + 访问控制)
前端·架构·node.js·状态模式·nestjs
全栈王校长7 天前
Nest IoC 依赖注入 - 一次彻底讲明白
nestjs
全栈王校长7 天前
前端转后端?用 Vue 的思维学 NestJS,真香!
nestjs
当时只道寻常7 天前
NestJS Redis 原子限流守卫 防刷防攻击
后端·nestjs
踩着两条虫7 天前
VTJ.PRO 在线应用开发平台的Open API 与外部集成
低代码·ai编程·nestjs
www_stdio8 天前
🚀 从 Event Loop 到 AI Agent:我的 Node.js 全栈进阶之路
前端·node.js·nestjs
Bigger8 天前
🚀 开源发布!从 0 到 1,使用 Next.js + Nest.js 构建全栈自动化数据分析 AI Agent
agent·nestjs·next.js
踩着两条虫10 天前
VTJ.PRO 在线应用开发平台的数据库与基础设施
数据库·架构·nestjs
踩着两条虫11 天前
VTJ.PRO 在线应用开发平台的后端模块系统
后端·架构·nestjs
踩着两条虫11 天前
VTJ.PRO 在线应用开发平台的业务模块(应用、DSL、模板、订单、智能体、技能)
后端·agent·nestjs