【问题标题】:xmlHttpRequest status = 0xmlHttpRequest 状态 = 0
【发布时间】:2016-01-10 18:05:13
【问题描述】:

我有一个网站(wagtail CMS)在域:8000 的 AWS 上运行,我的 API 在域:8801 上运行

在我的网页上,我尝试使用 JS 从 API 获取一些信息(Access-Control-Allow-Origin 标头在 API 中正确设置,它是一个基于 django 的应用程序)

不幸的是,无论我尝试访问什么,以下代码都只返回 xhr.status = 0 和空的 responseText。

当我将 domain:8000 放在 xhr.open('GET','http://domain:8000',true) 时,一切正常,我看到了我的 html 代码。

function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
if (xhr.status != 200) {
  alert( "ERR" ); --always ERR in browser
    } 
    else {
        alert( "SUCCESS" );
    }
}

在 API 端,我在服务器控制台中看到了我的所有请求,status=200。

【问题讨论】:

  • 同源策略规定协议、域和端口必须匹配,所以这里没有意外,它不应该工作,这是一种安全措施。
  • Access-Control-Allow-Origin 不允许绕过吗?
  • @arjabbar - 如果设置正确,它应该,但看到它使用相同的端口,而不是不同的端口,它可能设置不正确。
  • @adeneo 当我将 url 更改为 google.com 时,这是我在 chrome 控制台中看到的:XMLHttpRequest cannot load google.com。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'domain:8000' 不允许访问。响应的 HTTP 状态代码为 405。我的 url 是空的

标签: javascript ajax django amazon-web-services


【解决方案1】:

您需要等待 xhr.readyState == 4 才能使 xhr.status 完全有效(实际上我认为它在 3 时有效,但让我们与野外 99.999% 的代码保持一致)

function load() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://domain:8801/api/', true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status != 200) {
                alert( "ERR" ); --always ERR in browser
            } 
            else {
                alert( "SUCCESS" );
            }
        }
    };
    xhr.send();
}

【讨论】:

  • alert(xhr.status) 而不是 'ERR' ...您正在获得什么状态...您确定您使用的域允许 CORS?
【解决方案2】:

您应该使用回调函数来捕获来自使用XMLHttpRequest 对象的请求的响应。改为这样做:

xhr.addEventListener('readystatechange', function() {
    if (xhr.status != 200) {
      alert( "ERR" ); --always ERR in browser
    } else {
      alert( "SUCCESS" );
    }
  }
});

Look here for docs and an examples on doing that.

【讨论】:

  • open()的第三个参数设置为true时,请求是同步的,显然不需要回调
  • @arjabbar 伙计们,我忽略了这件事!更改为 false,现在它工作得很好
  • 第三个参数设置为 true 使调用异步不同步。 @massive_dynamic,您应该避免同步 xhr。您的问题已通过结合此答案和等待 xhr 在检查状态之前完成,即 xhr.readyState == 4 得到解决
  • 这很有趣。我从不使用最后一个论点。在 Javascript 中使用同步请求对我来说很奇怪。
猜你喜欢
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 2012-12-30
相关资源
最近更新 更多