Sometimes, we want to use Axios interceptors with JavaScript.
In this article, we’ll look at how to use Axios interceptors with JavaScript.
How to use Axios interceptors with JavaScript?
To use Axios interceptors with JavaScript, we call axios.interceptors.request.use
to add a request interceptor.
And we call axios.interceptors.response.use
to add a response interceptor.
For instance, we write
axios.interceptors.request.use(
(config) => {
if (DEBUG) {
console.info(config);
}
return config;
},
(error) => {
if (DEBUG) {
console.error(error);
}
return Promise.reject(error);
}
);
axios.interceptors.response.use(
(response) => {
if (response.config.parse) {
// ...
}
return response;
},
(error) => {
return Promise.reject(error.message);
}
);
to call both methods to add a request and response interceptor.
We call axios.interceptors.request.use
with a callback to do something with the request config
and return it.
The 2nd argument is a function that handlers request errors.
Then we call axios.interceptors.response.use
with a function that gets the response and do something with it.
The 2nd argument is a function that handlers error responses and return a rejected promise with the error content.
Conclusion
To use Axios interceptors with JavaScript, we call axios.interceptors.request.use
to add a request interceptor.
And we call axios.interceptors.response.use
to add a response interceptor.