Retry Axios POST requests with timeout for each retry attempt

21.3k Views Asked by At

I have a use case where i need to retry a Axios request for 3 times in case of any error and each retry attempt should timeout in 3 seconds if it doesnt get any response within 3 seconds. Below is the code i am using. It retries for 3 times but it doesnt timeout each retry attempt. How can i timeout each retry attempt ? Any code snippets will be helpful.

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

There are 1 best solutions below

1
On

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.

Given the above points, something like this should work:

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 [email protected] or above.