Prevent redirection of Xmlhttprequest

Viewed 77706

Is it possible to prevent the browser from following redirects when sending XMLHttpRequest-s (i.e. to get the redirect status code back and handle it myself)?

6 Answers

Not according to the W3C standard for the XMLHttpRequest object (emphasis added):

If the response is an HTTP redirect:

If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.

They were considering it for a future release:

This specification does not include the following features which are being considered for a future version of this specification:

  • Property to disable following redirects;

but the latest specification no longer mentions this.

No you there isn't any place in the API exposed by XMLHttpRequest that allows you to override its default behaviour of following a 301 or 302 automatically.

If the client is running IE on windows then you can use WinHTTP instead to set an option to prevent that behaviour but thats a very limiting solution.

I extended user's answer to include an abort() call. It seems like this prevents the server from sending too much data when all you want is the redirect url.

var url = 'the url'
var http = new XMLHttpRequest();
http.open('GET', url);
http.onreadystatechange = function() {
    if (this.readyState === this.DONE) {
        console.log(this.responseURL)
        this.abort() // This seems to stop the response
    }
}
http.send()

In real life I wrapped the above code in a promise, but it made the code hard to read.

Also, I don't understand why getting the redirect url needs to be this difficult, but that is a question for another time and place.

It is not possible to handle redirect or 302 status at client side as answered in other comments. However you can prevent redirection. To do that you can set request header "X-Requested-With" with "XMLHttpRequest" xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); This should be done after open but before send. Example below

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
   if (this.readyState == 4 && this.status == 200) {
         reqObj.success(JSON.parse(this.responseText))
   } else if (this.status != 200) {
         reqObj.error(this.statusText)
   }
};
xhttp.open(reqObj.type, reqObj.url, reqObj.async);
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhttp.send();
Related