Nest核心组件 - 中间件

7/5/2023 NodejsNestjs

# 2.4 中间件(Middlewares)

中间件在 NestJS 中用于处理 HTTP 请求和响应。它是一个函数,可以在控制器之前或之后执行,从而可以在请求到达控制器之前对请求进行预处理,或在响应离开控制器之前对响应进行处理。

# 2.4.1 创建一个中间件

让我们来创建一个简单的中间件。在 src 目录下创建一个新的文件 logger.middleware.ts,并编写以下代码:

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request ${req.method} ${req.url}`);
    next();
  }
}
1
2
3
4
5
6
7
8
9
10

在上面的代码中,我们创建了一个实现了 NestMiddleware 接口的中间件类 LoggerMiddleware。NestMiddleware 接口要求中间件类实现 use 方法,该方法将会在每个请求中被调用。

在 use 方法中,我们可以访问请求对象 req 和响应对象 res,并执行我们需要的任何操作。在这个例子中,我们简单地记录了每个请求的方法和 URL。

# 2.4.2 注册中间件

要让中间件生效,我们需要将它注册到应用程序中。打开 src/app.module.ts 文件,并添加以下代码:

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';
import { LoggerMiddleware } from './logger.middleware';

@Module({
  imports: [CatsModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

在上面的代码中,我们实现了 NestModule 接口,并在 configure 方法中使用 consumer.apply(LoggerMiddleware).forRoutes('*') 来将 LoggerMiddleware 注册为全局中间件。

forRoutes('*') 表示该中间件将应用于所有路由。你也可以指定特定的路由或控制器来使用中间件,例如 forRoutes('cats') 表示该中间件将仅应用于 /cats 路径。

编辑时间: 7/5/2023, 10:00:00 AM