-
Star
(144)
You must be signed in to star a gist -
Fork
(36)
You must be signed in to fork a gist
-
-
Save yajra/5f5551649b20c8f668aec48549ef5c1f to your computer and use it in GitHub Desktop.
// Add a 401 response interceptor | |
window.axios.interceptors.response.use(function (response) { | |
return response; | |
}, function (error) { | |
if (401 === error.response.status) { | |
swal({ | |
title: "Session Expired", | |
text: "Your session has expired. Would you like to be redirected to the login page?", | |
type: "warning", | |
showCancelButton: true, | |
confirmButtonColor: "#DD6B55", | |
confirmButtonText: "Yes", | |
closeOnConfirm: false | |
}, function(){ | |
window.location = '/login'; | |
return Promise.reject(error) | |
}); | |
} else { | |
return Promise.reject(error); | |
} | |
}); |
Isn't using window.loction inefficient? Also, m not able to use any other routing. Can anyone suggest a better way? Thanks
Thanks you bro !!😎.
Watch out for false positives: If you use the same Axios instance to query other domains than your back end and that domain responds with status 401 your code will trigger.
Consider using a dedicated Axios instance to query other domains, or add something like that to the if (401 === error.response.status)
condition:
&& isSameOrigin(error.response.request.responseURL)
/**
* @param {string} url
* @return {boolean}
*/
const isSameOrigin = url => {
return new URL(window.location.href).origin === new URL(url).origin;
}
Good Point. Thanks.
I have a question?
What should I do if the API returns the 401 error code when the password does not match?
@hungpurdie You need the API to tell you that 401 is because of password mismatch specifically. In the following example the API responds 401 with a "Bad credentials." message only in that specific case:
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (
isSameOrigin(error.response?.request?.responseURL)
&& error.response?.status === 401
&& error.response?.data?.message !== 'Bad credentials.'
) {
// Do something
}
return Promise.reject(error);
}
);
In case of redirect to login page you do not fulfill the promise. You must return
Promise.reject(error);
afterwindow.location
Agreed. return Promise.reject(error)
needs to be called no matter what.
Gist adjusted and included the reject call. Thanks!
Awesome, great work!
For those who just want to reload the page without any message displayed:
window.axios.interceptors.response.use(function (response) { return response; }, function (error) { if (401 === error.response.status) { window.location.reload(true); } else { return Promise.reject(error); } });