# 中间件

  • 概述:Middleware实在路由处理程序之前调用的函数。中间件函数可以访问requestresponse对象,以及应用程序的next()中间件函数
  • 使用cli生成中间件
nest g mi middleware_name [file_path] --no-spec --flat

中间件可以执行以下任务

  • 执行任何代码
  • requestresponse对象进行更改
  • 结束请求-响应周期
  • 调用堆栈中的下一个中间件函数

# 创建中间件

# 类中间件

  • 概述:可以使用函数或者带有@Injectable()修饰的类中实现中间件。该类需要实现抽象类NestMiddlewareuse()接口。
import { Injectable, NestMiddleware } from '@nestjs/common'
import type { Request, Response, NextFunctioin } from 'express'

@Injectable()
export class TestMiddleware implements NestMiddleware {
  // 实现 use 接口
  use(req: Request, res: Response, next: NextFunctioin) {
    console.log('请求之前')
    next()
    console.log('请求之后')
  }
}

# 函数中间件

  • 函数中间件没有任何特殊要求。
import type { Request, Response, NextFunctioin } from 'express'

export function middleware(req: Request, res: Response, next: NextFunctioin) {
  console.log('请求之前')
  next()
  console.log('请求之后')
}

# 应用中间件

  • 概述:模块类通过实现抽象类NestModuleconfigure()接口。来设置应用中间件。
方法 描述 参数
apply() 实现的应用的中间件类 Middleware/Middleware[]
forRoutes() 为符合条件的路由使用中间件 string/string[]/Controller/Controller[]/{ path: string, method: RequestMethod.GET }
exclude() 排除不使用中间件的路由 string/string[]/{ path: string, method: RequestMethod.GET }
import { NestModule } from '@nestjs/common'
import { LoggerMiddleware } from './middleware/logger.middleware.ts'

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .exclude(
        { path: 'test', method: RequestMethod.GET }
      )
      .forRoutes('*', 'test', LoggerMiddleware)
  }
}

# 全局中间件





 


import { TestMiddleware } from '..'

// ... 
const app = await NestFactory.create(AppModule);
app.use(new TestMiddleware()) // 使用类中间件
app.use(middleware) // 使用函数式中间件