Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
axios interceptors for refresh token
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshToken = window.localStorage.getItem('refreshToken');
return axios.post('http://localhost:8000/auth/refresh', { refreshToken })
.then(({data}) => {
window.localStorage.setItem('token', data.token);
window.localStorage.setItem('refreshToken', data.refreshToken);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token;
originalRequest.headers['Authorization'] = 'Bearer ' + data.token;
return axios(originalRequest);
});
}
return Promise.reject(error);
});
@ryan-ds17

This comment has been minimized.

Copy link

@ryan-ds17 ryan-ds17 commented Dec 20, 2017

I have 2 async requests, each of them calls refresh_token api. How can I prevent extra api being called?

@mkjiau

This comment has been minimized.

Copy link

@mkjiau mkjiau commented Dec 27, 2017

@poohsen

This comment has been minimized.

Copy link

@poohsen poohsen commented Mar 12, 2018

why put the new token in defaults and originalRequest? won't one of them do?

@cyrielo

This comment has been minimized.

Copy link

@cyrielo cyrielo commented Apr 23, 2018

@poohsen the originalRequest is a cached configuration copy of the previous request that contains the expired token. The configuration, in this case the headers part also needs to be updated as it won't use the axios defaults even after it has been set.

@ervikashkumar

This comment has been minimized.

Copy link

@ervikashkumar ervikashkumar commented Jun 12, 2018

I have multiple ajax calls in a page in that case many ajax is getting 401 hence many refresh token calls .@poohsen can we avoid this ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment