首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用axios重试5xx请求

如何使用axios重试5xx请求
EN

Stack Overflow用户
提问于 2019-05-10 17:22:14
回答 8查看 39.1K关注 0票数 24

我想使用axios重试5xx请求。我的主请求位于try catch块的中间。我正在使用axios-retry库自动重试3次。

我使用的url会故意抛出一个503。然而,该请求并没有被重试,而是在我的catch块中被捕获。

代码语言:javascript
运行
复制
axiosRetry(axios, {
  retries: 3
});

let result;

const url = "https://httpstat.us/503";
const requestOptions = {
  url,
  method: "get",
  headers: {
  },
  data: {},
};


try {

  result = await axios(requestOptions);

} catch (err) {
  throw new Error("Failed to retry")
}

}
return result;
EN

回答 8

Stack Overflow用户

发布于 2020-09-26 18:34:14

axios-retry使用axios interceptor重试HTTP请求。它在then或catch处理请求或响应之前拦截它们。下面是工作代码片段。

代码语言:javascript
运行
复制
  const axios = require('axios');
  const axiosRetry = require('axios-retry');

  axiosRetry(axios, {
    retries: 3, // number of retries
    retryDelay: (retryCount) => {
      console.log(`retry attempt: ${retryCount}`);
      return retryCount * 2000; // time interval between retries
    },
    retryCondition: (error) => {
      // if retry condition is not specified, by default idempotent requests are retried
      return error.response.status === 503;
    },
  });

  const response = await axios({
    method: 'GET',
    url: 'https://httpstat.us/503',
  }).catch((err) => {
    if (err.response.status !== 200) {
      throw new Error(`API call failed with status code: ${err.response.status} after 3 retry attempts`);
    }
  });
票数 34
EN

Stack Overflow用户

发布于 2019-05-10 17:49:03

使用retry

代码语言:javascript
运行
复制
const retry = require('retry');

const operation = retry.operation({
  retries: 5,
  factor: 3,
  minTimeout: 1 * 1000,
  maxTimeout: 60 * 1000,
  randomize: true,
});

operation.attempt(async (currentAttempt) => {
  console.log('sending request: ', currentAttempt, ' attempt');
  try {

    await axios.put(...);

  } catch (e) {
    if (operation.retry(e)) { return; }
  }
});
票数 14
EN

Stack Overflow用户

发布于 2019-08-26 17:28:44

您可以使用axios拦截器拦截响应并重试请求。

您可以在thencatch处理请求或响应之前对其进行拦截。

请参阅axios interceptors

有两个流行的包已经利用axios拦截器来做到这一点:

这里有一个NPM compare链接,可以帮助您在两者之间做出选择

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56074531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档