Hassan khan
Last updated: August 22,2022
Axios interceptors in ReactJS
In simple words, Axios interceptors are just the process before the request is sent or a response received by a user. Once we set Axios interceptors then it will be applied to every request and response everywhere in the application.
Where to put Axios interceptors react?
The best place is to put it in the index file of react application.
Axios Interceptors example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import React from 'react'; import App from './App'; import ReactDOM from 'react-dom'; import axios from 'axios'; // Request interceptor axios.interceptors.request.use(function (config) { //Add logic before request is sent return config; }, function (error) { // Add logic with request error return Promise.reject(error); }); // Response interceptor axios.interceptors.response.use(function (res) { // Add your own logic here // We are checking just status code if (res.status === 200) { console.log('Response Success'); } return res; }, function (err) { //handle your error in response return Promise.reject(err); }); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
In the above example, we have created two interceptors and placed them on the index page of the reactjs application, one for the request and another one for the response. These interceptors will execute before every request or response.
You can copy the above code and test here to see the difference.