In my Reactjs app , I want to add an interceptor which can append some headers to some backend responses
So, I tried this :
JavaScript
x
12
12
1
export default function App() {
2
axios.interceptors.response.use(
3
(config)=> {
4
config.headers['myheader'] = 'myvalue'; // <-- THIS IS MY CUSTOM HEADERS
5
return config;
6
},
7
(error) => {
8
// ON ERREOR
9
})
10
11
);
12
And I suppose like that that my header would be append in every back-end response. But that doesn’t seem to work.
Suggestions ??
Advertisement
Answer
Add a request interceptor
JavaScript
1
13
13
1
axios.interceptors.request.use(
2
config => {
3
const token = localStorage.getItem('auth_token');
4
if (token) {
5
config.headers['Authorization'] = 'Bearer ' + token;
6
}
7
config.headers['Content-Type'] = 'application/json';
8
return config;
9
},
10
error => {
11
Promise.reject(error)
12
});
13
Add a response interceptor
JavaScript
1
32
32
1
axios.interceptors.response.use((response) => { // block to handle success case
2
return response
3
}, function (error) { // block to handle error case
4
const originalRequest = error.config;
5
6
if (error.response.status === 401 && originalRequest.url ===
7
'http://dummydomain.com/auth/token') { // Added this condition to avoid infinite loop
8
9
10
// Redirect to any unauthorised route to avoid infinite loop...
11
return Promise.reject(error);
12
}
13
14
if (error.response.status === 401 && !originalRequest._retry) { // Code inside this block will refresh the auth token
15
16
originalRequest._retry = true;
17
const refreshToken = 'xxxxxxxxxx'; // Write the logic or call here the function which is having the login to refresh the token.
18
return axios.post('/auth/token',
19
{
20
"refresh_token": refreshToken
21
})
22
.then(res => {
23
if (res.status === 201) {
24
localStorage.setItem('auth_token',res.data);
25
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('auth_token');
26
return axios(originalRequest);
27
}
28
})
29
}
30
return Promise.reject(error);
31
});
32
Click here to see the topic in detail.