# 中间件

来源：https://docs.nestjs.com/middleware

中间件是一个在路由处理器**之前**被调用的函数。中间件函数可以访问应用请求-响应周期中的[请求](https://expressjs.com/en/4x/api.html#req)对象、[响应](https://expressjs.com/en/4x/api.html#res)对象，以及 `next()` 中间件函数。**下一个**中间件函数通常用名为 `next` 的变量来表示。

![客户端的 HTTP 请求先经过中间件，再交给路由处理器](./assets/Middlewares_1.png)

默认情况下，Nest 中间件等同于 [Express](https://expressjs.com/en/guide/using-middleware.html) 中间件。Express 官方文档对中间件能力的描述如下：

<blockquote class="external">
  中间件函数可以完成以下任务：
  <ul>
    <li>执行任意代码。</li>
    <li>修改请求对象与响应对象。</li>
    <li>结束请求-响应周期。</li>
    <li>调用栈中的下一个中间件函数。</li>
    <li>如果当前中间件函数没有结束请求-响应周期，它必须调用 <code>next()</code> 把控制权交给下一个中间件函数。否则，请求将一直挂起。</li>
  </ul>
</blockquote>

自定义的 Nest 中间件既可以写成函数，也可以写成用 `@Injectable()` 装饰器标注的类。类需要实现 `NestMiddleware` 接口，而函数没有任何特殊要求。我们先从实现一个简单的中间件类开始。

> warning **警告** Express 与 Fastify 处理中间件的方式不同，方法签名也不同；Node 适配器则使用 Express 的签名。详情参见 [HTTP 适配器](/http/performance#middleware)章节。

```typescript

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

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Request...');
    next();
  }
}
```

#### 依赖注入

Nest 中间件完整支持依赖注入。与提供者和控制器一样，中间件类可以**注入依赖**，只要这些依赖在同一模块内可用即可。和通常一样，依赖通过 `constructor` 注入。

#### 应用中间件

中间件不在 `@Module()` 装饰器中注册，而是在模块类的 `configure()` 方法里设置。包含中间件的模块必须实现 `NestModule` 接口。下面我们在 `AppModule` 层级设置 `LoggerMiddleware`。

```typescript

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

@Module({
  imports: [CatsModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('cats');
  }
}
```

在上面的示例中，`LoggerMiddleware` 被应用到 `CatsController` 中定义的 `/cats` 路由处理器上。若要把中间件限定到特定的请求方法，请向 `forRoutes()` 方法传入一个包含路由 `path` 与请求 `method` 的对象。下面的示例导入了 `RequestMethod` 枚举，用以引用所需的请求方法。

```typescript

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

@Module({
  imports: [CatsModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes({ path: 'cats', method: RequestMethod.GET });
  }
}
```

> info **提示** `configure()` 方法可以是异步的。用 `async` 声明它，就能在方法体内 `await` 某个异步操作的完成。

> warning **警告** 在 Express 与 Node 适配器下，Nest 默认会注册 `json` 与 `urlencoded` 请求体解析器（在 Express 上是 `express.json()` 和 `express.urlencoded()`，在 Node 上是适配器内置的解析器）。若想通过 `MiddlewareConsumer` 自定义这些解析器，请在使用 `NestFactory.create()` 创建应用时把 `bodyParser` 选项设为 `false`，以禁用默认解析器。

#### 路由通配符

中间件同样支持基于模式的路由。例如，命名通配符（`*splat`）可匹配路由中任意字符组合。在下面的示例中，凡是以 `abcd/` 开头的路由，中间件都会执行，无论后面跟着多少个字符。

```typescript
forRoutes({
  path: 'abcd/*splat',
  method: RequestMethod.ALL,
});
```

> info **提示** `splat` 只是通配符参数的名字，没有特殊含义。你可以用任何名字，例如 `*wildcard`。

`'abcd/*splat'` 路由路径可匹配 `abcd/1`、`abcd/123`、`abcd/abc` 等等。基于字符串的路径会把连字符（`-`）和点（`.`）按字面解释。不过，后面不带任何字符的 `abcd/` 并不匹配。要让它也能匹配，请把通配符包进花括号，使它成为可选项：

```typescript
forRoutes({
  path: 'abcd/{*splat}',
  method: RequestMethod.ALL,
});
```

> warning **警告** 单个普通的字符串路径在各适配器上匹配子路径的方式并不相同。在 Express 与 Node 适配器下，`forRoutes('cats')` 也会对 `/cats/breed` 这类子路径执行中间件；而在 Fastify 上，它只匹配 `/cats`。若要在所有适配器上都匹配 `/cats` 及其子路径，请把斜杠放进可选通配符里：`forRoutes('cats{/*splat&#125;')`。

#### 中间件消费者

`MiddlewareConsumer` 是一个辅助类，提供若干内置方法来管理中间件。它们都可以用[流式风格](https://en.wikipedia.org/wiki/Fluent_interface)**链式**调用。`forRoutes()` 方法接受单个字符串、多个字符串、一个 `RouteInfo` 对象、一个控制器类，或多个控制器类。大多数情况下，你会传入一个以逗号分隔的**控制器**列表。下面是一个只含单个控制器的示例：

```typescript

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

@Module({
  imports: [CatsModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes(CatsController);
  }
}
```

> info **提示** `apply()` 方法既可以接受单个中间件，也可以接受多个参数来指定<a href="/middleware#multiple-middleware">多个中间件</a>。

#### 排除路由

要把某些路由**排除**在中间件之外，请使用 `exclude()` 方法。它接受单个字符串、多个字符串，或一个用于标识要排除路由的 `RouteInfo` 对象：

```typescript
consumer
  .apply(LoggerMiddleware)
  .exclude(
    { path: 'cats', method: RequestMethod.GET },
    { path: 'cats', method: RequestMethod.POST },
    'cats/{*splat}',
  )
  .forRoutes(CatsController);
```

在上面的示例中，`LoggerMiddleware` 绑定到 `CatsController` 内定义的所有路由，**除了**与传给 `exclude()` 的三个条目相匹配的那些路由。

> info **提示** `exclude()` 方法借助 [path-to-regexp](https://github.com/pillarjs/path-to-regexp#parameters) 包支持通配符参数。

传给 `exclude()` 的路径以不含[全局前缀](/faq/global-prefix)的形式书写，Nest 会自动为它们补上该前缀，除非对应路由本身已被排除在前缀之外。如果某个排除项匹配到的路径已被排除在全局前缀之外，且不含参数或通配符，那么该路径也会跳过这个中间件——它是以不带前缀的方式提供服务的。这一匹配遵循路由器的大小写敏感设置。

```typescript
// main.ts
app.setGlobalPrefix('api', { exclude: ['health', 'health/ready'] });

// app.module.ts
consumer
  .apply(LoggerMiddleware)
  .exclude('health', 'health/*splat')
  .forRoutes('*splat');
```

这里，`health/*splat` 也让 `/health/ready` 跳过该中间件。它本身并不匹配 `/health`，所以还要一并列出 `health`。

#### 函数式中间件

我们一直在用的 `LoggerMiddleware` 类非常精简：没有成员，没有额外方法，也不依赖任何东西。这样的中间件可以定义为普通函数，而不必写成类。这类中间件被称为**函数式中间件**。我们把 logger 中间件从类改写为函数，以说明两者的差异：

```typescript

import type { Request, Response, NextFunction } from 'express';

export function logger(req: Request, res: Response, next: NextFunction) {
  console.log('Request...');
  next();
}
```

然后在 `AppModule` 中使用它：

```typescript

consumer
  .apply(logger)
  .forRoutes(CatsController);
```

> info **提示** 只要你的中间件不需要任何依赖，就请考虑使用**函数式中间件**。

#### 多个中间件

要绑定多个按顺序执行的中间件，请向 `apply()` 方法传入逗号分隔的列表：

```typescript
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
```

#### 全局中间件

要一次性把中间件绑定到所有已注册的路由上，请使用 `INestApplication` 实例的 `use()` 方法：

```typescript

const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(process.env.PORT ?? 3000);
```

> info **提示** 用 `app.use()` 注册的全局中间件无法访问 DI 容器，因此这类场景请使用[函数式中间件](middleware#functional-middleware)。或者改用类中间件，并在 `AppModule`（或其他任何模块）中用 `.forRoutes('*')` 绑定它。

#### 错误处理

当中间件抛出异常时，Nest 的[异常层](/exception-filters)会捕获它并发送相应的响应，就像处理路由处理器抛出的异常一样。推荐的做法是抛出 `HttpException`（或其内置子类，例如 `UnauthorizedException`）：

```typescript

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

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    if (!req.headers.authorization) {
      throw new UnauthorizedException();
    }
    next();
  }
}
```

如果中间件是异步的，请把 `use()` 声明为 `async`（或返回 `Promise`），这样被拒绝的 promise 才能被转发到异常层：

```typescript

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly authService: AuthService) {}

  async use(req: Request, res: Response, next: NextFunction) {
    const user = await this.authService.verify(req.headers.authorization);
    if (!user) {
      throw new UnauthorizedException();
    }
    req['user'] = user;
    next();
  }
}
```

你也可以把错误传给 `next()`。这在包装那些通过回调上报失败的既有 Express 风格中间件时很有用：

```typescript
use(req: Request, res: Response, next: NextFunction) {
  if (!req.headers.authorization) {
    return next(new UnauthorizedException());
  }
  next();
}
```

> warning **警告** 由于中间件在选择路由处理器之前运行，只有**全局**异常过滤器（通过 `app.useGlobalFilters()` 或 `APP_FILTER` 标记注册）才能捕获中间件抛出的异常。方法级与控制器级的过滤器不会被调用，也不支持用 `@UseFilters()` 把过滤器绑定到中间件类上。

> info **提示** 用 `app.use()` 注册的中间件由底层 HTTP 平台（Express 或 Fastify）处理，而不是由 Nest 的 `MiddlewareModule` 处理。请优先在通过 `MiddlewareConsumer` 绑定的中间件里抛出错误（或调用 `next(err)`），以便异常层能够处理它们。
