【问题标题】:Get Status Code on CORS Request获取 CORS 请求的状态码
【发布时间】:2016-08-06 11:54:41
【问题描述】:

您如何 return 来自 CORS 请求的响应代码?我可以从 onload 事件中获取它,但我似乎无法将其取出并创建一个 return 以便我可以捕获它以进行值检查。

这是我基于http://www.html5rocks.com/en/tutorials/cors/的代码:

createCORSRequest: function(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {

      // Check if the XMLHttpRequest object has a "withCredentials" property.
      // "withCredentials" only exists on XMLHTTPRequest2 objects.
      xhr.open(method, url, true);

    } else if (typeof XDomainRequest != "undefined") {

      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);

    } else {

      // Otherwise, CORS is not supported by the browser.
      xhr = null;

    }
    return xhr;
  },

  makeCorsRequest: function() {
    // All HTML5 Rocks properties support CORS.
    var me = this;
    var url = 'http://google.com';
    var sCode = '';

    var xhr = me.createCORSRequest('GET', url);
    console.log('xhr', xhr);
    if (!xhr) {
      alert('CORS not supported');
      return;
    }

    // Response handlers.
    xhr.onload = function() {
      var text = xhr.responseText;
      var sCode = xhr.status;
      // var title = getTitle(text);
      // alert('Response from CORS request to ' + url + ': ' + xhr.status);
    };

    xhr.onreadystatechange = function() {
      console.log(this.status);
      sCode = this.status;
    }

    xhr.onerror = function() {
      alert('Woops, there was an error making the request.');
    };

    xhr.send();
    return sCode; // this returns an empty string or the initial value set to it and not from `onload` event
  }

【问题讨论】:

  • 看起来您在返回响应之前返回了“状态”。您可能需要考虑到onerroronload 等事件将被异步触发,只有这样您才能使用status 代码。回调或承诺可能会有所帮助。
  • 你能分享一下你是如何打电话给makeCorsRequest的吗?
  • 嗨@AnkitMishra。我正在使用 AngularJS,所以我从我的工厂调用它:statusCode = $payments.makeCorsRequest();
  • 哦,我明白了,您需要将 makeCorsRequest 设为 Promise 或使用 callback。因为您当前的代码期望同步响应,但在 XHR 请求之上是异步的,因此 sCode 会在没有被分配的情况下返回。
  • @AnkitMishra:不确定如何用 Angular 编写。我假设它是以我为 $http 编写成功/错误回调的方式实现的?

标签: javascript angularjs cors


【解决方案1】:

一种方法是在 JS 中使用 Callback,因为我们可以将 JavaScript 中的函数作为参数传递给其他函数,并从内部异步调用它们。

我对您的代码进行了一些修改,使其异步响应,并添加了相关的 cmets。请注意下面callback 的使用。

//make few changes to make it asynchronous.
makeCorsRequest: function(callback) {
    // All HTML5 Rocks properties support CORS.
    var me = this;
    var url = 'http://google.com';
    var sCode = '';

    var xhr = me.createCORSRequest('GET', url);
    console.log('xhr', xhr);
    if (!xhr) {
      callback('CORS not supported');
      return;
    }

    // Response handlers.
    xhr.onload = function() {
      var text = xhr.responseText;
      var sCode = xhr.status;
      // var title = getTitle(text);
      // alert('Response from CORS request to ' + url + ': ' + xhr.status);
      callback(null, text);
    };

    xhr.onreadystatechange = function() {
      console.log(this.status);
      callback(this.status);
    }

    xhr.onerror = function() {
      callback('Woops, there was an error making the request.');
    };

    xhr.send();
  }

//this function would be the callback, it would be called 'Asynchronously' form XHR events with err or real data. First parameter generally indicates error.
function handleCorsResponse(err, data) {
   //check if error occurred
   if (err) {
      //error handling here
   }

  //if no error occurred, proceed.
   console.log(data);
}

//let's call `makeCorsRequest` with `handleCorsResponse` as a parameter.
$payments.makeCorsRequest(handleCorsResponse);

注意:更好的推荐方法是使用Promise

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 2018-05-04
    • 2017-09-06
    • 2021-08-28
    • 1970-01-01
    • 2020-07-18
    • 2016-02-05
    • 1970-01-01
    • 2019-07-22
    相关资源
    最近更新 更多