Created
October 5, 2017 18:46
-
-
Save culttm/a8c3ca85032c4b0cc67037425f150c44 to your computer and use it in GitHub Desktop.
axios interceptors for refresh token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ?