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

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

相关推荐
XiaoYu20027 天前
第3章 Nest.js拦截器
前端·ai编程·nestjs
XiaoYu20028 天前
第2章 Nest.js入门
前端·ai编程·nestjs
实习生小黄9 天前
NestJS 调试方案
后端·nestjs
当时只道寻常12 天前
NestJS 如何配置环境变量
nestjs
濮水大叔24 天前
VonaJS是如何做到文件级别精确HMR(热更新)的?
typescript·node.js·nestjs
ovensi24 天前
告别笨重的 ELK,拥抱轻量级 PLG:NestJS 日志监控实战指南
nestjs
ovensi25 天前
Docker+NestJS+ELK:从零搭建全链路日志监控系统
后端·nestjs
Gogo8161 个月前
nestjs 的项目启动
nestjs
没头发的卓卓1 个月前
新手入门:nest基本使用规则(适合零基础小白)
nestjs