# @foundatiofx/fetchclient 中文文档

规范地址：https://npmcn.com/package/%40foundatiofx/fetchclient/

版本：1\.3\.4
npm 元数据更新时间：2026-07-29T00:51:39.750Z
中文译文更新时间：2026-11-15T10:19:42.158Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40foundatiofx/fetchclient
原文对照：https://npmcn.com/package/%40foundatiofx/fetchclient/?lang=original
项目主页：https://github.com/FoundatioFx/FetchClient#readme
源码仓库：https://github.com/FoundatioFx/FetchClient

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：456 kB，58 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2025-08-28T02:29:37.451Z
- 最新版本发布：2026-07-29T00:51:39.381Z
- 近 30 天下载量：2888（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：13（近 12 个月 10 个）

## 中文简介

![Foundatio](https://raw.githubusercontent.com/foundatiofx/foundatio/master/media/foundatio-dark-bg.svg#gh-dark-mode-only "Foundatio") \[Fundatio\] (英语)[https://raw.githubusercontent.com/foundatiofx/foundatio/master/media/foundatio.svg#gh-light-mode-仅限](https://raw.githubusercontent.com/foundatiofx/foundatio/master/media/foundatio.svg#gh-light-mode-only) "风"

## 安装

```sh
npm install @foundatiofx/fetchclient
```

也可以使用：`pnpm add @foundatiofx/fetchclient`、`yarn add @foundatiofx/fetchclient`、`bun add @foundatiofx/fetchclient`

## README

![Foundatio](https://raw.githubusercontent.com/foundatiofx/foundatio/master/media/foundatio-dark-bg.svg#gh-dark-mode-only "Foundatio") ![Foundatio](https://raw.githubusercontent.com/foundatiofx/foundatio/master/media/foundatio.svg#gh-light-mode-only "Foundatio")

[![NPM](https://img.shields.io/npm/v/%40foundatiofx%2Ffetchclient)](https://www.npmjs.com/package/@foundatiofx/fetchclient) [![JSR](https://jsr.io/badges/@foundatiofx/fetchclient)](https://jsr.io/@foundatiofx/fetchclient) [![Build status](https://github.com/foundatiofx/foundatio/workflows/Build/badge.svg)](https://github.com/foundatiofx/foundatio/actions) [![Discord](https://img.shields.io/discord/715744504891703319)](https://discord.gg/6HxgFCx)

抓取 client 是一个小的, 键入的包装器周围 `fetch` 与JSON帮手, 中间软件、限制费率、断路器、超时和友好错误 处理.

## 特征

-   **输入的 JSON 助手** - 说吧 `getJSON`, (中文(简体) ), `queryJSON`, (中文(简体) ), `postJSON`, (中文(简体) ), `putJSON`, (中文(简体) ), `patchJSON`, (中文(简体) ), `deleteJSON`
-   **两个 API 样式** - 功能或班级 - 你的选择
-   **响应缓存** - 基于 TTL 的缓存, 带有分组无效标记
-   **中间软件** - 拦截请求/答复记录、认证、转换
-   **限制费率** - 具有自动信头探测器的域内费率限制
-   **断路器** - 防止服务下降时出现连锁故障
-   **超时** - 请求中止信号支持的超时
-   **处理错误** - RFC 7807问题细节支持
-   **测试** - 在测试中嘲弄HTTP的模拟记录

## 安装

```bash
npm install @foundatiofx/fetchclient
```

## 快速示例

Fettleclient 工作有两种方式 - 选择您喜欢的样式 :

### 函数 API

```ts
import { getJSON, postJSON, setBaseUrl } from "@foundatiofx/fetchclient";

setBaseUrl("https://api.example.com");

const { data: users } = await getJSON<User[]>("/users");
const { data: created } = await postJSON<User>("/users", { name: "Alice" });
```

或使用 `getFetchClient()` 避免多重进口:

```ts
import { getFetchClient, setBaseUrl } from "@foundatiofx/fetchclient";

setBaseUrl("https://api.example.com");

const client = getFetchClient();
const { data: users } = await client.getJSON<User[]>("/users");
const { data: created } = await client.postJSON<User>("/users", {
  name: "Alice",
});
```

### 基于类的 API

```ts
import { FetchClient } from "@foundatiofx/fetchclient";

const client = new FetchClient({ baseUrl: "https://api.example.com" });
const { data } = await client.getJSON<User[]>("/users");
```

## 缓存

```ts
const response = await client.getJSON<User>("/api/users/1", {
  cacheKey: ["users", "1"],
  cacheDuration: 60000, // 1 minute
  cacheTags: ["users"],
});

// Invalidate by tag
client.cache.deleteByTag("users");
```

## 中间软件

```ts
import { useMiddleware } from "@foundatiofx/fetchclient";

useMiddleware(async (ctx, next) => {
  console.log("Request:", ctx.request.url);
  await next();
  console.log("Response:", ctx.response?.status);
});
```

## 限制费率

```ts
import { usePerDomainRateLimit } from "@foundatiofx/fetchclient";

usePerDomainRateLimit({
  maxRequests: 100,
  windowSeconds: 60,
  updateFromHeaders: true, // Respect API rate limit headers
});
```

## 断路器

```ts
import { useCircuitBreaker } from "@foundatiofx/fetchclient";

useCircuitBreaker({
  failureThreshold: 5,
  openDurationMs: 30000,
});

// When API fails repeatedly, circuit opens
// Requests return 503 immediately without hitting the API
```

## 测试

```ts
import { FetchClientProvider } from "@foundatiofx/fetchclient";
import { MockRegistry } from "@foundatiofx/fetchclient/mocks";

const mocks = new MockRegistry();
mocks.onGet("/api/users").reply(200, [{ id: 1, name: "Alice" }]);

const client = new FetchClient();
mocks.install(client);

const { data } = await client.getJSON("/api/users");
// data = [{ id: 1, name: "Alice" }]
```

## 文档

-   指南实例( E) : [https://fetchclient.foundatio.dev 页面存档备份,存于互联网档案馆](https://fetchclient.foundatio.dev/)
    -   [开始](https://fetchclient.foundatio.dev/guide/getting-started)
    -   [缓存](https://fetchclient.foundatio.dev/guide/caching)
    -   [中间软件](https://fetchclient.foundatio.dev/guide/middleware)
    -   [限制费率](https://fetchclient.foundatio.dev/guide/rate-limiting)
    -   [断路器](https://fetchclient.foundatio.dev/guide/circuit-breaker)
    -   [处理错误](https://fetchclient.foundatio.dev/guide/error-handling)
    -   [测试](https://fetchclient.foundatio.dev/guide/testing)
-   API 参考 : [https://jsr.io/@foundatiofx/fetch客户端/doc](https://jsr.io/@foundatiofx/fetchclient/doc)

* * *

麻省理工学院 [创始人](https://exceptionless.com/)

## 常见问题

### @foundatiofx/fetchclient 是什么？

\[Fundatio\] \(英语\)https://raw\.githubusercontent\.com/foundatiofx/foundatio/master/media/foundatio\.svg\#gh-light-mode-仅限 "风"

### 如何安装 @foundatiofx/fetchclient？

在项目目录运行 npm install @foundatiofx/fetchclient，或使用 pnpm add / yarn add / bun add。

### @foundatiofx/fetchclient 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @foundatiofx/fetchclient 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @foundatiofx/fetchclient 可以商用吗？

@foundatiofx/fetchclient 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @foundatiofx/fetchclient 的下载量有多少？

根据 npm 官方下载统计，@foundatiofx/fetchclient 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,888 次，日均约 96 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @foundatiofx/fetchclient 还在维护吗？

最新版本 1\.3\.4 发布于 2026/07/29（3 个月前）；至今共发布 13 个版本，其中过去 12 个月发布了 10 个；首次发布于 2025/08/28。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

