Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Follow redirect (302) in XMLHttpRequest

Using Firefox I am trying to download some data from Google Drive using XMLHttpRequest. In the debug console it gives me [302 Moved Temporarily] and the data i receive is empty. How can i get XMLHttpRequest to follow a redirect response? Also I am using https if it changes things.

like image 307
PureGero Avatar asked Sep 08 '13 03:09

PureGero


People also ask

Does XMLHttpRequest follow redirect?

Using a XMLHttpRequest in async mode, the redirects are followed and it works as expected,; but in synchronous mode it fails.

How do I follow a postman redirect?

To do this, open the Settings tab of your request and toggle off the Automatically follow redirects option. Force your request to follow the original HTTP method. To do so, open the Settings tab of the request and toggle on the Follow original HTTP method option.


1 Answers

Basiclly you get the Location using xhr.getResponseHeader("Location"). In this case you could just send another XMLHttpRequest to this location using the same parameter:

function ajax(url /* ,params */, callback) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
      // return if not ready state 4
      if (this.readyState !== 4) {
        return;
      }

      // check for redirect
      if (this.status === 302 /* or may any other redirect? */) {
        var location = this.getResponseHeader("Location");
        return ajax.call(this, location /*params*/, callback);
      } 

      // return data
      var data = JSON.parse(this.responseText);
      callback(data);
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}
like image 173
kpalatzky Avatar answered Oct 21 '22 07:10

kpalatzky