Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning redirect as response to XHR request

Tags:

ajax

http

What happens if the browser receives a redirect response to an ajax request?

like image 431
Vasil Avatar asked Nov 11 '08 22:11

Vasil


People also ask

Does XHR follow redirect?

Yes, XMLHttpRequest object (according to the standard) must automatically handle redirection without giving the client code a chance to do anything about it.

Does fetch follow redirects?

Normally, fetch transparently follows HTTP-redirects, like 301, 302 etc.

What is response redirect Javascript?

redirect() The redirect() method of the Response interface returns a Response resulting in a redirect to the specified URL. Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page's request and redirect it as desired.


1 Answers

What happens if the browser receives a redirect response to an ajax request?

If the server sends a redirect (aka a 302 response plus a Location: header) the redirect is automatically followed by the browser. The response to the second request (assuming it also isn't another redirect) is what is exposed to your program.

In fact, you don't have the ability to detect whether a 302 response has occurred. If the 302 redirect leads to a 200, then your program acts identically as if the original request led directly to a 200.

This has been both my experience and the behavior called out in the spec.

2016 Update: Time has passed, and the good news is that the new fetch() API is spec'd to offer finer-grained control of how redirects are handled, with default behavior similar to XHR. That said, it only works where fetch() is implemented natively. Polyfill versions of fetch()—which are based on XHR—continue to have XHR's limitations. Fortunately, native browser support seems to be rounding out nicely.

like image 107
greim Avatar answered Sep 20 '22 17:09

greim