如何使用 axios 重试 5xx 请求

新手上路,请多包涵

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

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

 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;

原文由 Kay 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 551
1 个回答

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

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

async function makeHTTPCall() {
    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`);
        }
    });
}

makeHTTPCall();

原文由 ns15 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题