简体   繁体   中英

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM