Follow redirect (302) in XMLHttpRequest

use*_*349 12 javascript xmlhttprequest google-drive-api

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.

arc*_*hos 7

基本上你可以使用 来获取位置xhr.getResponseHeader("Location")。在这种情况下,您可以XMLHttpRequest使用相同的参数将另一个发送到该位置:

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();
}
Run Code Online (Sandbox Code Playgroud)