@ethanresnick/retry-axios

中文文档
2.6.1发布于 2022/11/19Apache-2.0TypeScriptESM + CJS零依赖近 30 天下载 1.1万

用 Axios 重试 HTTP 请求 .

中文使用文档
文档目录4 节
  1. 安装
  2. 使用量
  3. 如何运作
  4. 许可证

重试轴

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

NPM Version GitHub Actions Known Vulnerabilities codecov style badge

安装

npm install retry-axios

使用量

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

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

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

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

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

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

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

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

你有很多选择...

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上的逻辑需要同步,您可以返回一个承诺,那么重试只有在承诺解决后才会被执行:

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();
          }
        });
      });
    }
  }
});

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

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 会告诉你,如果一个请求通常会重审:

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

版本与发布记录

@ethanresnick/retry-axios 共发布 2 个版本,首次发布于 2022/11/19;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.6.1latest2022/11/193 年前
2.6.02022/11/193 年前

关于 @ethanresnick/retry-axios 的常见问题

@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 和提交记录判断。