# @ethanresnick/retry-axios 中文文档

规范地址：https://npmcn.com/package/%40ethanresnick/retry-axios/

版本：2\.6\.1
npm 元数据更新时间：2022-11-19T04:12:29.408Z
中文译文更新时间：2026-11-13T23:29:37.808Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40ethanresnick/retry-axios
原文对照：https://npmcn.com/package/%40ethanresnick/retry-axios/?lang=original
项目主页：https://github.com/JustinBeckwith/retry-axios#readme
源码仓库：https://github.com/JustinBeckwith/retry-axios

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

- 包体积（解压后）：72.7 kB，11 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=10\.7\.0
- 运行依赖：0 个
- peer 依赖：axios \*
- 首次发布：2022-11-19T03:28:28.381Z
- 最新版本发布：2022-11-19T04:12:29.312Z
- 近 30 天下载量：11188（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：2（近 12 个月 0 个）

## 中文简介

用 Axios 重试 HTTP 请求 .

## 安装

```sh
npm install @ethanresnick/retry-axios
```

也可以使用：`pnpm add @ethanresnick/retry-axios`、`yarn add @ethanresnick/retry-axios`、`bun add @ethanresnick/retry-axios`

## README

# 重试轴

> 使用 Axios 截取器自动重试失败的请求 。 超级灵活。 以指数回转方式建造.

[![NPM Version](https://img.shields.io/npm/v/retry-axios.svg)](https://npmjs.org/package/retry-axios) [![GitHub Actions](https://github.com/JustinBeckwith/retry-axios/workflows/ci/badge.svg)](https://github.com/JustinBeckwith/retry-axios/actions/) [![Known Vulnerabilities](https://snyk.io/test/github/JustinBeckwith/retry-axios/badge.svg)](https://snyk.io/test/github/JustinBeckwith/retry-axios) [![codecov](https://codecov.io/gh/JustinBeckwith/retry-axios/branch/main/graph/badge.svg)](https://codecov.io/gh/JustinBeckwith/retry-axios) [![style badge](https://img.shields.io/badge/code%20style-Google%20%E2%98%82%EF%B8%8F-blue.svg)](https://www.npmjs.com/package/gts)

## 安装

```sh
npm install retry-axios
```

## 使用量

要使用此库,请同时导入 `axios`数字 :

```js
// Just import rax and your favorite version of axios
const rax = require('retry-axios');
const axios = require('axios');
```

或者,如果您使用 TypeScript / es 模块:

```js
import * as rax from 'retry-axios';
import axios from 'axios';
```

您可以附加到全球 `axios` 对象,并默认重试三次:

```js
const interceptorId = rax.attach();
const res = await axios('https://test.local');
```

或者您可以创建自己的 arxios 实例来提出范围化请求 :

```js
const myAxiosInstance = axios.create();
myAxiosInstance.defaults.raxConfig = {
  instance: myAxiosInstance
};
const interceptorId = rax.attach(myAxiosInstance);
const res = await myAxiosInstance.get('https://test.local');
```

你有很多选择...

```js
const interceptorId = rax.attach();
const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    // Retry 3 times on requests that return a response (500, etc) before giving up.  Defaults to 3.
    retry: 3,

    // Retry twice on errors that don't return a response (ENOTFOUND, ETIMEDOUT, etc).
    noResponseRetries: 2,

    // Milliseconds to delay at first.  Defaults to 100. Only considered when backoffType is 'static'
    retryDelay: 100,

    // HTTP methods to automatically retry.  Defaults to:
    // ['GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT']
    httpMethodsToRetry: ['GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT'],

    // The response status codes to retry.  Supports a double
    // array with a list of ranges.  Defaults to:
    // [[100, 199], [429, 429], [500, 599]]
    statusCodesToRetry: [[100, 199], [429, 429], [500, 599]],

    // If you are using a non static instance of Axios you need
    // to pass that instance here (const ax = axios.create())
    instance: ax,

    // You can set the backoff type.
    // options are 'exponential' (default), 'static' or 'linear'
    backoffType: 'exponential',

    // You can detect when a retry is happening, and figure out how many
    // retry attempts have been made
    onRetryAttempt: err => {
      const cfg = rax.getConfig(err);
      console.log(`Retry attempt #${cfg.currentRetryAttempt}`);
    }
  }
});
```

如果Retry Attrempt上的逻辑需要同步,您可以返回一个承诺,那么重试只有在承诺解决后才会被执行:

```js
const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    onRetryAttempt: err => {
      return new Promise((resolve, reject) => {
        // call a custom asynchronous function
        refreshToken(err, function(token, error) {
          if (!error) {
            window.localStorage.setItem('token', token);
            resolve();
          } else {
            reject();
          }
        });
      });
    }
  }
});
```

或者,如果你想,你可以只是决定 它是否应该重试:

```js
const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    // Override the decision making process on if you should retry
    shouldRetry: err => {
      const cfg = rax.getConfig(err);
      return true;
    }
  }
});
```

如果您想要添加自定义重试逻辑而不重复太多内置逻辑, `rax.shouldRetryRequest` 会告诉你,如果一个请求通常会重审:

```js
const res = await axios({
  url: 'https://test.local',
  raxConfig: {
    // Override the decision making process on if you should retry
    shouldRetry: err => {
      const cfg = rax.getConfig(err);
      if (cfg.currentRetryAttempt >= cfg.retry) return false // ensure max retries is always respected

      // Always retry this status text, regardless of code or request type
      if (err.response.statusText.includes('Try again')) return true

      // Handle the request based on your other config options, e.g. `statusCodesToRetry`
      return rax.shouldRetryRequest(err)
    }
  }
});
```

## 如何运作

此库附带一个 `interceptor` 给一个Axios实例 你通过API。 这样你就可以选择哪个版本 `axios` 你可以在同一条请求的管道上 制造许多拦截器.

## 许可证

[阿帕奇 - 2.0](https://npmcn.com/package/%40ethanresnick/retry-axios/LICENSE)

## 常见问题

### @ethanresnick/retry-axios 是什么？

用 Axios 重试 HTTP 请求 \.

### 如何安装 @ethanresnick/retry-axios？

在项目目录运行 npm install @ethanresnick/retry-axios，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：axios（\*）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @ethanresnick/retry-axios 支持 TypeScript 吗？

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

### @ethanresnick/retry-axios 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @ethanresnick/retry-axios 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=10\.7\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @ethanresnick/retry-axios 可以商用吗？

@ethanresnick/retry-axios 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @ethanresnick/retry-axios 的下载量有多少？

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

### @ethanresnick/retry-axios 还在维护吗？

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

