Cannot handle 302 redirect in ajax and why? [duplicate]

You shouldn’t redirect the call when it’s an XHR but respond with a 401 Unauthorized and handle this in your callbacks. I don’t know ASP.NET but I did something similar with Spring Security.

Heres the concept:

  • Get the authenticated state
  • Check the headers for X-Requested-With: XMLHttpRequest
  • When found and not authenticated respond with 401 Unauthorized
  • When not found and not authenticated redirect.

The bottom line is that XHR calls need to be handled differently then other HTTP requests in some cases. You should only redirect a XHR if the same resource is at another location.

To answer your question

You can’t handle redirects with XHR callbacks because the browser takes care of them automatically. You will only get back what at the redirected location.

Leave a Comment