【问题标题】:Retry Axios POST requests with timeout for each retry attempt每次重试都超时重试 Axios POST 请求
【发布时间】:2020-02-09 23:02:34
【问题描述】:

我有一个用例,如果出现任何错误,我需要重试 Axios 请求 3 次,如果在 3 秒内没有得到任何响应,则每次重试尝试应该在 3 秒内超时。下面是我正在使用的代码。它重试 3 次,但每次重试都不会超时。如何使每次重试尝试超时?任何代码 sn-ps 都会有所帮助。

const axiosRetry = require('axios-retry');
axiosRetry(axios, { retries: 3 });

axios.post(url,payload,{headers:header})
 .then((response) =>{
    console.log('Response is *****'+JSON.stringify(response));

})
.catch((err) =>{
    console.log('Error occurred'+err);

}); 

【问题讨论】:

    标签: node.js axios axios-retry


    【解决方案1】:

    1) 我没有看到您在代码中的任何位置将 timeout 设置为 3 秒。

    2) 默认情况下,axios-retry 将请求超时解释为全局值,因此如果您需要它在每次重试 3 秒后超时,请设置shouldResetTimeout: true

    3) 默认情况下,axios-retry 不会重试超时请求(即带有ECONNABORTED 代码的请求)和像POST 这样的非幂等请求。设置一个自定义 retryCondition 来改变它。

    鉴于以上几点,这样的事情应该可以工作:

    const axios = require('axios').default;
    const axiosRetry = require('axios-retry');
    axiosRetry(axios, {
      retries: 3,
      shouldResetTimeout: true,
      retryCondition: (_error) => true // retry no matter what
    });
    
    axios.post(url, payload, {headers: header, timeout: 3000})
      .then((res) => {
        console.log('Response is *****', res);
    
      })
      .catch((err) => {
        console.log('Error occurred' + err);
      });
    

    另外,请务必使用axios@0.19.1 或更高版本。

    【讨论】:

    • 感谢您的回答。对我来说 axios retry with .post 在我添加您建议的行之前不起作用:retryCondition: () => true
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2020-08-09
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多