22

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.

Towkir
  • 3,889
  • 2
  • 22
  • 41
PureGero
  • 937
  • 2
  • 8
  • 16
  • 2
    XMLHttpRequest will automatically follow the redirect. What data are you trying to retrieve? – Khanh TO Sep 08 '13 at 03:14
  • 1
    http://stackoverflow.com/a/20854800/1531945 may have an answer in case it's CORS request – Konstantin Pelepelin Nov 19 '14 at 15:30
  • 2
    Be careful you may need CORS for both the redirect and the page it is redirected to (with redirects, like POST's, it might not work at all, see the linked answer in the other comments). – rogerdpack Jan 05 '18 at 06:47

1 Answers1

7

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();
}
kpalatzky
  • 1,213
  • 1
  • 11
  • 26