Need some advice about handling 302 redirects from Ajax
See original GitHub issueSummary
We have a single page app based on Vue.js which uses Axios to make API calls. When a user’s session expires, API calls start returning a 302 redirect to the login page. Since its a single page app, sometimes users may just browse around directly in the app, therefore only making AJAX calls and not reloading the main index.html file.
When this happens, the 302’s are basically swallowed and the user is not redirected and the app breaks.
To complicate matters a bit further, the login page is based on a federated login service in Azure, so it’s on a different domain. This causes the browser to throw the following CORS error:
XMLHttpRequest cannot load login.microsoftonline.com.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
I tried to use an interceptor but the error.response object is undefined, so I cannot even tell what the HTTP status of the response was. So the best I can come up with is that when error.response is undefined to assume it was a 302 and assume I need to forward the user to the login page:
axios.interceptors.response.use((response) => {
return response
}, (error) => {
// we can't seem to catch the 302 status code as an error,
// however, since it redirects to another domain (login.microsoftonline.com) it causes
// a CORS error which makes error.response be undefined here. This assumes that any time
// error.response is undefined that we need to redirect to the login page
if (typeof error.response === 'undefined') {
window.location = 'https://login.microsoftonline.com'
} else {
return Promise.reject(error)
}
})
Is this the best we can do? Any further suggestions?
Context
- Vue.js, vue-router single page app
- axios version: v0.16.0
- Environment: chrome 58, windows 10
Issue Analytics
- State:
- Created 6 years ago
- Reactions:25
- Comments:13 (2 by maintainers)
Browsers always follow redirects for XHRs or fetch() requests. There is no library that could prevent the redirect. What you need to do on your server-side is distinguish between XHR requests and normal browser navigation requests and send either a 403 w/ JSON and specify the URL you want to redirect to in there or send a 302 if the request is being made by a browser navigation request. You can do this a couple different ways, but I’ll list some here assuming you’re using Express:
Check the
req.xhr
to respond based on its boolean valueUse
res.format()
to respond based on what the client acceptsBy default axios sends an
Accept
header ofapplication/json, text/plain, */*
where as browser generally send theAccept
header withtext/html
being listed first.Then on your client-side you would use something like this when using either of the above solutions:
Yes, I have the same issue. It is critical enough to consider alternatives to axios