Retry Axios
If you have been coding in javascript for a while, you'd probably have known about Axios. It is a famous JS library for making HTTP request. Whether you are back-end or front-end developer, Axios is essential to access API services.
In this post, I'm going to show how to equip Axios with retry capability i.e resend HTTP request when server doesn't answer.
Retry-Axios second most popular retry add-on for Axios.
Install using the below command
npm install retry-axios
Below is the working code
const rax = require('retry-axios');
const axios = require('axios');
rax.attach();
const myRequest = async () => {
try {
const myConfig = {
raxConfig: {
retry: 5, // number of retry when facing 4xx or 5xx
noResponseRetries: 5, // number of retry when facing connection error
onRetryAttempt: err => {
const cfg = rax.getConfig(err);
console.log(`Retry attempt #${cfg.currentRetryAttempt}`); // track current trial
}
},
timeout: 50 // don't forget this one
}
const req = await axios.get('https://mock.codes/200', myConfig);
console.log(req.data);
} catch (error) {
console.log(error);
}
}
myRequest();
I basically attached retry-axios
object to Axios. My part is handling config for the request.
That's it! Now we can make Axios more reliable in sending HTTP request. We can have multiple configuration, below is an example
Hope this helps.
No comments:
Post a Comment
If you have any doubts, Please let me know