I want to do a redirect from ajax requests. When a session expires my backend redirects to the login page instead of sending data. But as it has been discussed on StackOverflow before, ajax does not handle redirects.
Instead of updating all my ajax requests one by one to handle the status 401
, I am overriding them with ajaxSetup
:
$.ajaxSetup({
beforeSend:(xhr) => {
console.log(xhr);
console.log(xhr.status);
if (xhr.status === 401) {
window.location.replace(_baseUrl);
}
}
});
I am getting the required status for the redirects but the problem is I am not being able to access the status
variable from the XMLHttpRequest
request.
console.log(xhr);
:
...
status: 401
statusCode: ƒ (e)
statusText: "Unauthorized"
then: ƒ (t,i,o)
[[Prototype]]: Object
console.log(xhr.status);
:
undefined
CodePudding user response:
You can use .ajaxComplete()
event instead of $.ajaxSetup()
. Try this
$(document).ajaxComplete(function( event, xhr, settings ) {
console.log(xhr);
console.log(xhr.status);
if (xhr.status === 401) {
window.location.replace(_baseUrl);
}
});