I need to setup a global interceptor for all my axios calls. I'm defining them inside vuex actions and I need that if there is a 429 status code, an action is called and then after that actions is made, a retry with the original request is made. I'm learning about interceptors but I don't know how to properly setup it,and if it will work outside the export default. Can anyone help me?
axios.interceptors.use( (response) => {
// if no status error code is returned get the response
return response
}, (error) => {
console.log(error)
// here I need to retry the ajax call after that my loadProxy action is made and a 429 status code is sent from the server
return Promise.reject(error);
})
export default new Vuex.Store({
actions: {
loadProxy({ commit }) {
// here I have an axios get request to fetch a proxy from an API
},
fetchData({ commit, state }) {
// here I fetch the data to use in my app, sometimes due to many requests I need to refresh the proxy ip to let the app continue working
}
}
})
The response object in Axios' interceptor contains a config object. (See here)
You can use that to re-initiate the request with the original configuration.
An example:
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response.status === 429) {
// If the error has status code 429, retry the request
return axios.request(error.config);
}
return Promise.reject(error);
});
To use a Vuex action inside the interceptor callback, you can first define the store as a variable, then call the dispatch function inside the callback. Like this:
const store = new Vuex.Store({
// define store...
})
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response.status === 429) {
store.dispatch("YOUR_ACTION");
return axios.request(error.config);
}
return Promise.reject(error);
});
export default store;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With