重试Axios POST请求,每次重试均超时

 收藏

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

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

}); 
回复
  • 爷不缺孙子 回复

    1) I don't see you setting timeout to 3 seconds anywhere in your code.

    2) By default, axios-retry interprets the request timeout as a global value, so if you need it to timeout after 3 seconds on each retry, set shouldResetTimeout: true.

    3) By default, axios-retry does not retry timed out requests (i.e. those with ECONNABORTED code) and non-idempotent requests like POST. Set a custom retryCondition to change that.

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

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

    Also, make sure to use axios@0.19.1 or above.