# HTTP 客户端

来源：https://docs.nestjs.com/application/http-client

大多数应用都会通过 HTTP 调用其他服务。`@nestjs/http-client` 包为此提供客户端，构建在 Node.js 内置的 `fetch` API 之上。它补齐了 `fetch` 缺少的东西：基础 URL、默认请求头、JSON 请求体、路径与查询参数、类型化响应、超时、重试、拦截器和具名客户端。它作为 Nest 模块来配置，并像其他提供者一样注入。

除了 `@nestjs/common` 与 `@nestjs/core`，该包没有其他依赖。所有方法都返回 Promise，因此你用 `await` 等待请求，用 `try`/`catch` 处理失败。如果你偏爱 Observable，参见[配合 RxJS 使用](/application/http-client#working-with-rxjs)。

> info **提示** 该包取代了基于 Axios 的 `@nestjs/axios` 中的 `HttpModule`（本章过去介绍的就是它）。`@nestjs/axios` 仍然可用。切换方法参见[从 @nestjs/axios 迁移](/application/http-client#migrating-from-nestjsaxios)。

#### 安装

首先，安装该包：

```bash
$ npm i --save @nestjs/http-client
```

#### 快速上手

把 `HttpClientModule` 导入发起请求的模块，并用 `register()` 方法注册客户端：

```typescript
@@filename(cats.module)
import { Module } from '@nestjs/common';
import { HttpClientModule } from '@nestjs/http-client';
import { CatsService } from './cats.service.js';

@Module({
  imports: [
    HttpClientModule.register({
      baseUrl: 'https://api.example.com/v1',
      timeout: '5s',
    }),
  ],
  providers: [CatsService],
})
export class CatsModule {}
```

然后注入 `HttpClient` 类：

```typescript
@@filename(cats.service)
import { Injectable } from '@nestjs/common';
import { HttpClient } from '@nestjs/http-client';
import type { Cat } from './interfaces/cat.interface.js';

@Injectable()
export class CatsService {
  constructor(private readonly http: HttpClient) {}

  async findAll(): Promise<Cat[]> {
    const { data } = await this.http.get<Cat[]>('/cats');
    return data;
  }
}
```

请求会发往 `https://api.example.com/v1/cats`。相对 URL 会以恰好一个 `/` 拼接到 `baseUrl` 之后，因此 `/v1` 前缀得以保留（而 `new URL('/cats', base)` 会丢掉它）。没有 `baseUrl` 的客户端要求使用绝对 URL。

与其他 `register()` 方法一样，每次调用都为导入它的模块创建一个客户端。要让客户端在所有模块中可注入，请设置 `isGlobal: true`。

#### 具名客户端

应用通常要与多个上游服务通信，每个服务都有自己的基础 URL、凭据和超时。给每个客户端一个 `name`：

```typescript
@@filename(repos.module)
@Module({
  imports: [
    HttpClientModule.register({
      name: 'github',
      baseUrl: 'https://api.github.com',
      headers: { accept: 'application/vnd.github+json' },
    }),
  ],
  providers: [ReposService],
})
export class ReposModule {}
```

并用 `@InjectHttpClient()` 装饰器注入它：

```typescript
@@filename(repos.service)
@Injectable()
export class ReposService {
  constructor(@InjectHttpClient('github') private readonly github: HttpClient) {}
}
```

未命名的客户端就是默认客户端，以 `HttpClient` 注入。`getHttpClientToken(name)` 函数返回客户端的注入标记，在测试和自定义提供者中很有用。

#### 应用级默认值

所有客户端共享的设置，例如 `user-agent` 请求头、超时、重试策略或日志拦截器，放进 `HttpClientModule.forRoot()`。在根模块中导入一次即可。它始终是全局的：

```typescript
@@filename(app.module)
@Module({
  imports: [
    HttpClientModule.forRoot({
      headers: { 'user-agent': 'cats-service/1.0' },
      timeout: '10s',
    }),
    CatsModule,
    ReposModule,
  ],
})
export class AppModule {}
```

`forRoot()` 本身不注册客户端，也不接受 `baseUrl`。客户端自身的设置优先于默认值，但有三处例外：请求头会合并（在客户端把某个请求头设为 `null` 可移除默认值）、重试设置逐字段合并、`forRoot()` 的拦截器先于客户端自身的拦截器运行。

#### 异步配置

要用其他提供者（例如[配置](/application/configuration#getting-started)一章中的 `ConfigService`）来构造客户端选项，请使用 `registerAsync()`：

```typescript
@@filename(repos.module)
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { HttpClientModule, type Duration } from '@nestjs/http-client';
import { ReposService } from './repos.service.js';

@Module({
  imports: [
    HttpClientModule.registerAsync({
      name: 'github',
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        baseUrl: config.getOrThrow<string>('GITHUB_API_URL'),
        headers: { authorization: `Bearer ${config.getOrThrow<string>('GITHUB_TOKEN')}` },
        timeout: config.get<Duration>('GITHUB_TIMEOUT', '5s'),
      }),
    }),
  ],
  providers: [ReposService],
})
export class ReposModule {}
```

工厂可以是 `async` 的。它返回与 `register()` 相同的选项，类型为 `HttpClientFactoryOptions`，但 `name`、`isGlobal`、`imports` 和拦截器类除外：Nest 需要在工厂运行之前用它们构建模块，因此它们要放在 `useFactory` 旁边。若工厂返回其中之一，应用会在启动时停止。

除了工厂，你也可以传入一个实现 `HttpClientOptionsFactory` 接口的类。Nest 会在客户端所在模块内实例化它，并调用其 `createHttpClientOptions()` 方法：

```typescript
@@filename(github-client.config)
@Injectable()
export class GithubClientConfig implements HttpClientOptionsFactory {
  constructor(private readonly config: ConfigService) {}

  createHttpClientOptions(): HttpClientFactoryOptions {
    return { baseUrl: this.config.getOrThrow<string>('GITHUB_API_URL') };
  }
}
```

```typescript
HttpClientModule.registerAsync({
  name: 'github',
  imports: [ConfigModule],
  useClass: GithubClientConfig,
});
```

要复用已存在的提供者而不是创建私有副本，请传入 `useExisting: GithubClientConfig`，并把导出它的模块放进 `imports`。`forRootAsync()` 的用法相同。它的 `useClass` 或 `useExisting` 类实现 `HttpClientModuleOptionsFactory`，并提供 `createHttpClientModuleOptions()` 方法。

#### 发起请求

客户端为每个 HTTP 动词提供一个方法：`get()`、`post()`、`put()`、`patch()`、`delete()`、`head()` 和 `options()`。每个方法接收一个 URL 和一个可选的选项对象，决议为 `HttpResponse`。`request()` 方法通过 `method` 选项指定动词。

```typescript
@@filename(repos.service)
@Injectable()
export class ReposService {
  constructor(@InjectHttpClient('github') private readonly github: HttpClient) {}

  async findAll(org: string): Promise<Repo[]> {
    const { data } = await this.github.get<Repo[]>('/orgs/:org/repos', {
      params: { org },
      query: { type: 'public', sort: 'updated', topic: ['nest', 'typescript'] },
    });
    return data;
  }

  async createIssue(owner: string, repo: string, issue: CreateIssueDto): Promise<Issue> {
    const { data } = await this.github.post<Issue>('/repos/:owner/:repo/issues', {
      params: { owner, repo },
      json: issue,
    });
    return data;
  }
}
```

这些选项与 Nest 控制器从请求中读取的内容相对应：

- `params` 填充路径中的 `:name` 分段，并进行 URI 编码。缺少值的分段会抛出错误，即使省略 `params` 也一样；键匹配不到任何分段，或值会把请求移到其他端点（空字符串、`.` 或 `..`）时同样抛出。
- `query` 是对象或 `URLSearchParams` 实例，会追加到 URL 中已有的查询串之后。数组会重复键（`topic=nest&topic=typescript`），`Date` 值会转成 ISO 字符串，`null` 与 `undefined` 值会被跳过。上面的第一个请求会发往 `https://api.github.com/orgs/nestjs/repos?type=public&sort=updated&topic=nest&topic=typescript`。
- `json` 用 `JSON.stringify()` 序列化，并设置 `content-type: application/json` 请求头（除非你自己设置）。
- `body` 原样传给 `fetch`：字符串、`Buffer`、`FormData`、`URLSearchParams`、`Blob`、Web 或 Node.js 流，或异步可迭代对象。`json` 与 `body` 只能传其一。带请求体的 `GET` 或 `HEAD` 请求会在发送任何内容之前抛出。
- `headers` 会合并到客户端请求头之上。值为 `null` 会移除某个请求头。
- `timeout`、`retry`、`signal`、`throwOnHttpError`、`redirect` 和 `dispatcher` 会为单次请求覆盖客户端设置，下文逐一说明。
- `context` 是自由格式对象，[拦截器](/application/http-client#interceptors)可以读取它。

类型参数（例如 `Repo[]`）描述的是 `data`。运行时不会做任何检查，因此对你无法控制的 API，请校验响应。`responseType` 选项控制响应体如何读取：

| `responseType` | `data` |
| --- | --- |
| `'auto'`（默认） | `content-type` 为 JSON（包括 `+json` 类型）时解析 JSON，否则为字符串。响应体为空时、`204` 与 `205` 响应、以及 `HEAD` 请求时为 `undefined`。`304` 响应默认像任何非 2xx 一样抛出；设置 `throwOnHttpError: false` 时其 `data` 为 `undefined`。 |
| `'json'` | 解析 JSON，无论内容类型。 |
| `'text'` | 字符串。 |
| `'arrayBuffer'` | `ArrayBuffer`。 |
| `'stream'` | Node.js `Readable`。参见[流式响应](/application/http-client#streaming-responses)。 |
| `'response'` | Web `Response`，其响应体未被读取。 |

`data` 的类型跟随 `responseType`，因此 `responseType: 'text'` 决议为 `HttpResponse<string>`。若成功响应的响应体本应是 JSON 却不合法，会以 `HttpParseError` 被拒绝。响应对象的结构如下：

```typescript
interface HttpResponse<T> {
  status: number;
  statusText: string;
  ok: boolean;
  headers: Headers; // Web Headers 对象：headers.get('etag')
  data: T;
  url: string; // 最终 URL，重定向之后
  request: HttpRequest; // 实际发送的请求，拦截器执行之后
}
```

#### 超时与取消

`fetch` 本身没有超时，只有 Node.js 内置 HTTP 客户端 undici 的 5 分钟上限。请为每个客户端设置 `timeout`，可以是毫秒数，也可以是 `'500ms'`、`'5s'`、`'2m'` 这样的时长字符串。无效值会在启动时失败，错误信息会指出是哪个选项。`0` 表示无超时，这也是默认值。

超时作用于**每次尝试**，而不是整个调用。它覆盖该次尝试的拦截器以及读取响应体的时间。对 `responseType: 'stream'` 与 `'response'`，它在响应头到达后即停止计时，因此长时间下载不会被截断。超时耗尽时，该次尝试以 `HttpTimeoutError` 失败，请求会像其他[瞬时故障](/application/http-client#retries)一样重试。

要取消请求，请把 `AbortSignal` 作为 `signal` 选项传入。它会与超时合并。被取消的请求以该 signal 的 `reason` 拒绝（与 `fetch` 一致），并且永不重试，即使在两次尝试之间等待时也一样。

由于存在重试，一次调用最多可能耗时 `尝试次数 × 超时`，再加上尝试之间的等待。要为整个调用设上限，请把截止时间作为 signal 传入：

```typescript
const { data } = await this.github.get<Repo>('/repos/:owner/:repo', {
  params: { owner, repo },
  signal: AbortSignal.timeout(10_000),
});
```

该截止时间会以名为 `TimeoutError` 的 `DOMException` 拒绝，`toHttpException()` 会把它映射为 `504 Gateway Timeout`，与 `HttpTimeoutError` 相同。要与其他 signal 组合，请使用 `AbortSignal.any([signal, AbortSignal.timeout(10_000)])`。

#### 重试

重试**默认开启**。在没有任何配置的情况下，客户端对 `GET`、`HEAD`、`OPTIONS`、`PUT` 和 `DELETE`（HTTP 定义为幂等的方法）最多尝试 3 次。它会在以下情况后重试：

- 连接错误，例如连接被拒绝或重置（包括读取响应体期间被重置），
- 单次尝试超时，
- `408`、`429`、`500`、`502`、`503` 和 `504` 响应。

两次尝试之间，客户端使用指数退避加完全抖动等待：第一次尝试后随机等待最多 200 ms，第二次后最多 400 ms，依此类推，上限 30 秒。响应头 `Retry-After`（以秒或 HTTP 日期表示）会取代退避时间。当它要求的等待超过上限时，客户端完全不等待，直接返回（或抛出）该 `429` 或 `503` 响应。请求体是流时永不重试，因为第一次尝试已将其消费。

`retry` 选项接受尝试次数、`false`（只尝试一次）或一个对象：

```typescript
HttpClientModule.register({
  name: 'github',
  baseUrl: 'https://api.github.com',
  retry: {
    attempts: 4, // 总共，含第一次请求
    backoff: { delay: '500ms', factor: 2, maxDelay: '5s', jitter: 'full' },
    retryIf: (error, attempt) => !(error instanceof HttpNetworkError),
    methods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'],
    statusCodes: [408, 429, 500, 502, 503, 504],
  },
}),
```

省略的字段保留默认值。`backoff` 也可以是函数，接收失败尝试的序号及其错误，返回一个时长。`jitter` 可以是 `'full'`、`'equal'`（至少为计算延迟的一半）或 `'none'`。`retryIf` 只会被问到客户端本来就会重试的失败，因此它只能收窄默认范围而不能扩大；要扩大请用 `methods` 与 `statusCodes`。它接收失败尝试的 `HttpResponseError`（含其 `body`）、`HttpTimeoutError` 或 `HttpNetworkError`。

重试设置是分层的：先是 `forRoot()`，再是客户端，最后是请求。每层只覆盖它设置的字段，后面的层可以在前面 `false` 之后重新开启重试。不过 `methods` 与 `statusCodes` 是**替换**默认列表，而不是追加。

`POST` 与 `PATCH` 不会重试，因为重复执行可能造成（例如）向客户重复扣款。当上游 API 支持幂等键时，请发送一个，并为该请求显式开启重试：

```typescript
const { data } = await this.payments.post<Charge>('/charges', {
  json: charge,
  headers: { 'idempotency-key': `charge-${order.id}` },
  retry: { methods: ['POST'] },
});
```

该键标识这次操作，因此每次尝试都发送同一个键，上游会返回原始结果而不会创建第二笔扣款。若改为在客户端上设置 `methods: ['POST']`，由于该列表会替换默认列表，`GET` 的重试也会一并停止。

> warning **警告** 重试会沿服务链成倍放大。如果服务 A 调用 B、B 调用 C，每一跳都尝试 3 次，那么一个失败的 C 请求会变成 9 次对 C 的调用，而且恰好在 C 已经吃紧时到来。只在一层重试，通常是调用外部依赖的那个服务，并对调用自家服务的客户端设置 `retry: false`。

#### 处理错误

请求会以以下错误之一被拒绝，它们都继承 `HttpClientError` 类：

| 错误 | 触发时机 | 字段 |
| --- | --- | --- |
| `HttpResponseError` | 上游返回非 2xx 状态。 | `status`、`statusText`、`headers`、`body`（解析后的 JSON，否则为文本）、`method`、`url` |
| `HttpTimeoutError` | 最后一次尝试的 `timeout` 耗尽。 | `timeoutMs`、`method`、`url` |
| `HttpNetworkError` | 连接失败：DNS、连接被拒绝或重置、TLS，或客户端拒绝的重定向（到其他源，或在 `redirect: 'error'` 时）。 | `cause`（例如 `cause.code` 为 `ECONNREFUSED`）、`method`、`url` |
| `HttpParseError` | 成功响应本应是 JSON 却不合法。 | `status`、`statusText`、`headers`、`body`（原始文本）、`method`、`url` |

被取消的请求以 signal 的 reason 拒绝，拦截器抛出的错误原样传播。客户端拒绝发送的请求（例如 `params` 值无效）以 `TypeError` 拒绝。若要把非 2xx 响应当作值接收，请在客户端或请求上设置 `throwOnHttpError: false`，并自行检查 `ok` 或 `status`。

如果这些错误从路由处理器逸出，Nest 会返回 `500 Internal Server Error`。但对你的 API 调用方来说，上游失败通常是 `502 Bad Gateway`，上游未及时响应则是 `504 Gateway Timeout`。`toHttpException()` 函数会相应地映射这些错误：

| 错误 | 变成 |
| --- | --- |
| `HttpResponseError` | `502 Bad Gateway`；当状态列在 `forward` 中时，返回上游状态与响应体 |
| `HttpTimeoutError`，或 `AbortSignal.timeout()` 截止时间产生的 `TimeoutError` | `504 Gateway Timeout` |
| `HttpNetworkError`、`HttpParseError` | `502 Bad Gateway` |
| 其他任何错误，包括 `HttpException` | 原样返回，由 Nest 照常处理 |

```typescript
@@filename(repos.service)
async findOne(owner: string, repo: string): Promise<Repo> {
  try {
    const { data } = await this.github.get<Repo>('/repos/:owner/:repo', {
      params: { owner, repo },
    });
    return data;
  } catch (error) {
    if (error instanceof HttpResponseError && error.status === 404) {
      throw new NotFoundException(`Repository ${owner}/${repo} not found`);
    }
    throw toHttpException(error);
  }
}
```

默认情况下，上游响应体不会传给调用方，因为它可能暴露上游内部细节。要把选定状态连同响应体一起透传（例如 `422` 的响应体告诉调用方该修什么），请使用 `toHttpException(error, options)`，把 `forward` 设为 `[422]`，或设为 `true` 以透传所有状态。原始错误会保留为异常的 `cause`。

Nest 内置的异常过滤器[不会记录](/exception-filters#exceptions-logging) `HttpException` 的日志，因此 `502` 或 `504` 不会留下痕迹。所以 `toHttpException()` 会为它转成 `5xx` 的每次失败记录日志，上下文为 `HttpClient`：

```text
ERROR [HttpClient] GET https://api.github.com/repos/nestjs/nest failed with 503 Service Unavailable; answering 502 Bad Gateway
```

当其他环节（例如你自己的异常过滤器）已经记录上游失败时，请把 `log` 选项设为 `false`。

与其在每个服务里映射错误，不如让它们原样逸出处理器，并在[异常过滤器](/exception-filters#binding-filters)中映射。这样调用点无需 `try`/`catch`，更外层的拦截器也仍能看到原始错误：

```typescript
@@filename(http-client-error.filter)
import { ArgumentsHost, Catch } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { HttpClientError, toHttpException } from '@nestjs/http-client';

@Catch(HttpClientError)
export class HttpClientErrorFilter extends BaseExceptionFilter {
  catch(error: HttpClientError, host: ArgumentsHost) {
    super.catch(toHttpException(error), host);
  }
}
```

`AbortSignal.timeout()` 截止时间不是 `HttpClientError`，因此如果使用截止时间，请把 `DOMException` 也加入 `@Catch()`。`toHttpException()` 返回 `HttpException`，所以在微服务或 WebSocket 处理器中，请自行把错误转成 `RpcException` 或 `WsException`。

> info **提示** 错误消息与错误对象最终会进入日志，因此客户端会让机密远离它们。消息中从不包含响应体，其中的 URL 查询值也会被掩码，例如 `GET https://api.example.com/users?email=***`。`url`、`headers` 和 `body` 字段是不可枚举的：你的代码可以读取它们，但日志记录器和 `JSON.stringify()` 会略过。

#### 拦截器

拦截器包裹客户端发出的每个请求。它接收请求和一个负责发送的 `next` 函数，并返回得到的 Web `Response`。最简单的形式是函数：

```typescript
@@filename(api-key.interceptor)
import type { HttpClientInterceptorFn } from '@nestjs/http-client';

export function apiKeyInterceptor(apiKey: string): HttpClientInterceptorFn {
  return (request, next) => {
    request.headers.set('x-api-key', apiKey);
    return next(request);
  };
}
```

`HttpRequest` 对象持有 `method`、`url`（`URL` 实例）、`headers`（`Headers` 实例）、`body`、`signal`、`attempt` 序号，以及请求的 `context`。你可以就地修改它，或把修改后的副本传给 `next()`。拦截器在状态检查**之前**看到响应，因此 `4xx` 或 `5xx` 响应也会经过它们。拦截器必须返回 `next()` 决议的结果，或返回自己的 `Response`。

当拦截器需要其他提供者时，请把它写成实现 `HttpClientInterceptor` 接口的类：

```typescript
@@filename(github-auth.interceptor)
import { Injectable } from '@nestjs/common';
import type { HttpClientInterceptor, HttpHandler, HttpRequest } from '@nestjs/http-client';
import { GithubTokenService } from './github-token.service.js';

@Injectable()
export class GithubAuthInterceptor implements HttpClientInterceptor {
  constructor(private readonly tokens: GithubTokenService) {}

  async intercept(request: HttpRequest, next: HttpHandler): Promise<Response> {
    request.headers.set('authorization', `Bearer ${await this.tokens.getToken()}`);
    return next(request);
  }
}
```

把拦截器放进 `register()` 或 `forRoot()` 的 `interceptors` 数组，或在异步变体中放在 `useFactory` 旁边：

```typescript
@@filename(repos.module)
@Module({
  imports: [
    HttpClientModule.register({
      name: 'github',
      baseUrl: 'https://api.github.com',
      interceptors: [GithubAuthInterceptor],
    }),
  ],
  providers: [GithubTokenService, GithubAuthInterceptor, ReposService],
})
export class ReposModule {}
```

Nest 在应用初始化时解析拦截器类，因此拦截器甚至可以依赖一个注入了同一客户端的服务。若该类是应用中任意位置的提供者（如上例的 `GithubAuthInterceptor`），就使用那个实例。否则 Nest 会在客户端自己的模块内创建它，该模块能看到全局提供者以及你在 `register()` 的 `imports` 选项中传入的模块。异步工厂也可以在其选项中返回拦截器，但只能是函数和实例，例如 `apiKeyInterceptor(config.getOrThrow('API_KEY'))`。

拦截器按列出顺序运行，第一个在最外层，`forRoot()` 的拦截器先于客户端自身的拦截器。它们**每次尝试运行一次**，因此重试会拿到新令牌，`request.attempt` 告诉它们这是第几次尝试。尝试失败时，`next()` 以 `HttpNetworkError`、`HttpTimeoutError` 或中止原因拒绝。因此拦截器是记录上游流量的好位置：

```typescript
@@filename(http-logging.interceptor)
import { Injectable, Logger } from '@nestjs/common';
import type { HttpClientInterceptor, HttpHandler, HttpRequest } from '@nestjs/http-client';

@Injectable()
export class HttpLoggingInterceptor implements HttpClientInterceptor {
  private readonly logger = new Logger('HttpClient');

  async intercept(request: HttpRequest, next: HttpHandler): Promise<Response> {
    const target = `${request.method} ${request.url.origin}${request.url.pathname}`;
    const start = performance.now();
    try {
      const response = await next(request);
      const ms = Math.round(performance.now() - start);
      this.logger.log(`${target} ${response.status} ${ms}ms (attempt ${request.attempt})`);
      return response;
    } catch (error) {
      this.logger.warn(`${target} failed: ${(error as Error).name} (attempt ${request.attempt})`);
      throw error;
    }
  }
}
```

用 `HttpClientModule.forRoot()` 注册，并设置 `interceptors: [HttpLoggingInterceptor]`，它就会记录每个客户端的请求。它记录路径而不含查询串，因为查询串常携带个人数据或密钥。

> info **提示** 做链路追踪时你不需要拦截器。[NestJS Observe](/observability/distributed-tracing#http-to-http) 会把每次出站 `fetch` 调用记录为 span，并把 trace id 传播给其他 Nest 服务。

#### 流式响应

要把大响应透传而不在内存中缓冲，请设置 `responseType: 'stream'`。`data` 是 Node.js `Readable`，你可以从路由处理器以 [`StreamableFile`](/http/file-upload#streaming-files) 返回它：

```typescript
@@filename(invoices.controller)
@Get(':id/pdf')
async download(@Param('id') id: string): Promise<StreamableFile> {
  const { data, headers } = await this.billing.get('/invoices/:id/pdf', {
    params: { id },
    responseType: 'stream',
  });
  return new StreamableFile(data, {
    type: headers.get('content-type') ?? 'application/pdf',
  });
}
```

响应头到达后超时即停止计时，而取消 `signal` 仍会中止下载。非 2xx 响应会照常被读取并作为 `HttpResponseError` 抛出。不要把上游的 `content-length` 请求头当作 `length` 选项传入：`fetch` 会解压 gzip 与 brotli 响应体，流可能比请求头声明的更长。要使用 Web `ReadableStream`，请用 `responseType: 'response'` 并读取 `data.body`。

#### 代理、TLS 与重定向

Node.js 的 `fetch` 运行在 undici 上，其默认 dispatcher 维护一个 keep-alive 连接池，因此常见场景无需配置。要改变连接池大小、经由代理，或使用自定义 TLS 设置（私有 CA 或客户端证书），请把 undici dispatcher 作为 `dispatcher` 选项传入：

```typescript
@@filename(partner.module)
import { readFileSync } from 'node:fs';
import { Agent } from 'undici';

@Module({
  imports: [
    HttpClientModule.register({
      name: 'partner',
      baseUrl: 'https://partner.example.com',
      dispatcher: new Agent({
        connections: 20,
        connect: {
          ca: readFileSync('certs/partner-ca.pem'),
          cert: readFileSync('certs/client.pem'),
          key: readFileSync('certs/client-key.pem'),
        },
      }),
    }),
  ],
})
export class PartnerModule {}
```

代理场景请传 `new ProxyAgent('http://proxy.internal:3128')`。Node.js 不从内置模块暴露这些类，因此请自行安装 `undici` 包（`@nestjs/http-client` 不依赖它），最好选用与你的 Node.js 版本内置的主版本一致。Node.js 的 `http.Agent`（Axios 可将其作为 `httpsAgent`）无法与 `fetch` 配合，编译也无法通过。若要改为按 `HTTP_PROXY`、`HTTPS_PROXY` 与 `NO_PROXY` 环境变量让所有客户端走代理，请在支持该特性的版本上用 `--use-env-proxy`（或设置 `NODE_USE_ENV_PROXY=1`）启动 Node.js。

`redirect` 选项控制 `3xx` 响应的处理方式。带 `baseUrl` 的客户端只跟随同源重定向，跳到其他主机会以 `HttpNetworkError` 失败，因为其请求头携带的是该上游的凭据（参见[安全性](/application/http-client#security)）。不带 `baseUrl` 的客户端允许 `fetch` 跟随任意重定向，在源变化时丢弃 `authorization` 与 `cookie` 请求头，但其他请求头不丢。

把 `redirect` 设为 `'follow'`，带 `baseUrl` 的客户端也会跟随任意重定向，适用于有意跳到其他主机的 API；设为 `'error'` 则在任何重定向时失败；设为 `'manual'` 则原样接收 `3xx` 响应。`3xx` 响应不算成功，因此请把 `'manual'` 与 `throwOnHttpError: false` 搭配使用，以便读取其 `location` 请求头。

#### 安全性

客户端防范了几类常见错误：

- **带 `baseUrl` 的客户端只向自己的源发送请求。** 同源的绝对 URL（例如分页链接）没问题，但其他主机的绝对 URL 会在发送任何内容前抛出。跳到其他主机的重定向同样会在那里重发请求前失败。客户端的请求头与拦截器携带该上游的凭据，而来自用户输入或上游响应的 URL 绝不应收到它们。要调用任意主机，请使用不带 `baseUrl` 的客户端；或对有意跳到其他主机的 API 使用 `redirect: 'follow'`。
- **路径参数会被编码。** 请把请求值放进 `params` 与 `query`，而不是用字符串插值拼接路径。它们会被 URI 编码，而 `..` 这样的 `params` 值会抛出，而不会把请求移到其他端点。
- **URL 中的凭据会被拒绝。** 像 `https://user:pass@example.com` 这样的 `baseUrl` 或请求 URL 会抛出。请改为在 `authorization` 请求头中发送凭据。含换行的请求头值会抛出，且消息中不会引用该值。
- **错误可以安全记录日志**，如[处理错误](/application/http-client#handling-errors)所述。

#### 测试

桩（stub）`fetch` 是测试调用外部 API 代码的最简便方式。把它传给 `HttpClientModule.forRoot()`，所有客户端都会使用它，同时保留各自的基础 URL、请求头、重试策略和拦截器。桩只需返回标准 `Response`：

```typescript
@@filename(repos.service.spec)
import { Test } from '@nestjs/testing';
import { HttpClientModule } from '@nestjs/http-client';
import { vi } from 'vitest';
import { ReposModule } from './repos.module.js';
import { ReposService } from './repos.service.js';

describe('ReposService', () => {
  const fetch = vi.fn<typeof globalThis.fetch>();
  let repos: ReposService;

  beforeEach(async () => {
    fetch.mockReset();
    const moduleRef = await Test.createTestingModule({
      imports: [HttpClientModule.forRoot({ fetch }), ReposModule],
    }).compile();
    await moduleRef.init();
    repos = moduleRef.get(ReposService);
  });

  it('lists the public repositories of an organization', async () => {
    fetch.mockResolvedValueOnce(Response.json([{ name: 'nest' }]));

    await expect(repos.findAll('nestjs')).resolves.toEqual([{ name: 'nest' }]);
    const [url] = fetch.mock.calls[0];
    expect(String(url)).toBe(
      'https://api.github.com/orgs/nestjs/repos?type=public&sort=updated&topic=nest&topic=typescript',
    );
  });

  it('retries a 503', async () => {
    fetch
      .mockResolvedValueOnce(new Response(null, { status: 503 }))
      .mockResolvedValueOnce(Response.json([]));

    await expect(repos.findAll('nestjs')).resolves.toEqual([]);
    expect(fetch).toHaveBeenCalledTimes(2);
  });
});
```

给每次调用单独的 `Response`，如上例的 `mockResolvedValueOnce()`：响应体只能读取一次，用 `mockResolvedValue()` 会把已读过的响应交给重试。自带 `fetch` 选项的客户端会保留它，因为客户端设置优先于 `forRoot()` 默认值。没有该选项的客户端每次请求都调用 `globalThis.fetch`，因此 `vi.stubGlobal('fetch', stub)` 也可行。

对已经调用了 `forRoot()` 的应用做端到端测试时，改为覆盖其选项。这会替换所有 `forRoot()` 选项，但直接传给 `forRoot()` 或放在 `useFactory` 旁边的拦截器除外，它们会继续运行：

```typescript
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
  .overrideProvider(HTTP_CLIENT_MODULE_OPTIONS)
  .useValue({ fetch })
  .compile();
```

要在测试中完全隔离 HTTP，可用 `overrideProvider(getHttpClientToken('github'))` 替换客户端本身。在 Nest 之外（例如脚本中），用 `new HttpClient(options)` 创建客户端。

#### 配合 RxJS 使用

要用 RxJS 操作符组合请求，把它包进 Observable。`defer()` 在 Observable 被订阅时发起请求，而 `from()` 会立即发起：

```typescript
import { defer } from 'rxjs';

const cats$ = defer(() => this.http.get<Cat[]>('/cats'));
```

两者都不会在取消订阅时取消请求。需要这样做时（例如配合 `switchMap()`），请把取消订阅接到 `AbortController`：

```typescript
import { Observable } from 'rxjs';

function fromRequest<T>(send: (signal: AbortSignal) => Promise<T>): Observable<T> {
  return new Observable<T>((subscriber) => {
    const controller = new AbortController();
    send(controller.signal).then(
      (value) => {
        subscriber.next(value);
        subscriber.complete();
      },
      (error) => subscriber.error(error),
    );
    return () => controller.abort();
  });
}

const cats$ = fromRequest((signal) => this.http.get<Cat[]>('/cats', { signal }));
```

#### 从 `@nestjs/axios` 迁移

`@nestjs/axios` 包仍然可用，迁移期间两个包可以并存。下表把它的特性映射到 `@nestjs/http-client`：

| `@nestjs/axios` | `@nestjs/http-client` |
| --- | --- |
| `HttpModule.register()` 配 `baseURL` | `HttpClientModule.register()` 配 `baseUrl` |
| `HttpModule.registerAsync()` | `HttpClientModule.registerAsync()`，且还接受 `name` |
| `HttpModuleOptionsFactory` 配 `createHttpOptions()` | `HttpClientOptionsFactory` 配 `createHttpClientOptions()` |
| `registerAsync()` 中的 `extraProviders` | 导出了这些提供者的模块，通过 `imports` 传入 |
| 每个导入模块一个 `HttpService` | 具名客户端，用 `@InjectHttpClient(name)` 注入 |
| `HttpService` 方法返回 Observable | `HttpClient` 方法返回 Promise |
| `firstValueFrom(this.httpService.get(url))` | `await this.http.get(url)` |
| `post(url, data)` | `post(url, options)`，数据放在 `json`（或 `body`）中 |
| 请求配置中的 `params` | `query`。数组重复键，而 Axios 写 `key[]=`。在 `@nestjs/http-client` 中，`params` 用于填充 `:name` 路径分段，匹配不到键时抛出。 |
| `response.headers['etag']` | `response.headers.get('etag')` |
| `AxiosError` 配 `error.response?.status` | `HttpResponseError` 配 `error.status` 与 `error.body` |
| `error.code === 'ECONNABORTED'` | `HttpTimeoutError` |
| `validateStatus: () => true` | `throwOnHttpError: false` |
| `axiosRef`（Axios 实例） | 没有底层实例。使用客户端选项，或把自定义函数作为 `fetch` 传入。 |
| `axiosRef.interceptors.request.use()` 与 `response.use()` | `interceptors`，一个函数同时处理请求与响应 |
| `httpsAgent` 或 `proxy` | `dispatcher`，一个 undici `Agent` 或 `ProxyAgent` |
| `maxRedirects: 0` | `redirect: 'manual'` |
| 不重试，除非加上 `axios-retry` | 幂等方法默认重试。`retry: false` 恢复 Axios 的行为。 |
| 整个请求的 `timeout` | 每次尝试的 `timeout`，也支持 `'5s'` 这样的字符串 |
| `onUploadProgress`、`onDownloadProgress` | 无对应能力。请自行统计流的字节数。 |
