Skip to content

Instantly share code, notes, and snippets.

@culttm
Created October 5, 2017 18:46
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save culttm/a8c3ca85032c4b0cc67037425f150c44 to your computer and use it in GitHub Desktop.
Save culttm/a8c3ca85032c4b0cc67037425f150c44 to your computer and use it in GitHub Desktop.
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);
});
@ervikashkumar
Copy link

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