Skip to content

Instantly share code, notes, and snippets.

@culttm
Created October 5, 2017 18:46
Show Gist options
  • Select an option

  • Save culttm/a8c3ca85032c4b0cc67037425f150c44 to your computer and use it in GitHub Desktop.

Select an option

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);
});
@ryan-ds17

Copy link
Copy Markdown

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

@mkjiau

mkjiau commented Dec 27, 2017

Copy link
Copy Markdown

@poohsen

poohsen commented Mar 12, 2018

Copy link
Copy Markdown

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

@cyrielo

cyrielo commented Apr 23, 2018

Copy link
Copy Markdown

@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

ervikashkumar commented Jun 12, 2018

Copy link
Copy Markdown

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