XHR状态未定义

时间:2017-11-08 23:48:14

标签: javascript xmlhttprequest cors

我尝试向REST API发送XHR请求,但我无法得到答案。

这是我的代码:

<script>
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://www.mocky.io/v2/5a083d8e2f0000c61ee61140", true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.onreadystatechange = function() {
    console.log("xhr.readyState: " + xhr.readyState);

    if (xhr.readyState === XMLHttpRequest.DONE) {
      console.log("xhr.status: " + xhr.status);

      if (xhr.status === 200) {
        console.log("xhr.responseText: " + xhr.responseText);

        var response = JSON.parse(xhr.responseText);
      }
    }
  }
  xhr.send();
  console.log("xhr.readyState: " + xhr.readyState);
  console.log("xhr.status: " + xhr.status);
</script>

当我执行它时,xhr.status仍然未定义,它永远不会进入if (xhr.status === 200)。我不知道为什么。有人能帮助我吗?

修改

我修复了JSON,但仍然有错误:

Google Chrome console showing an error.

错误大约是Access-Control-Allow-Origin

  

无法加载http://www.mocky.io/v2/5a083d8e2f0000c61ee61140:对预检请求的响应未通过访问控制检查:否&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。起源&#39; null&#39;因此不允许访问。响应的HTTP状态代码为403。

所以,我读了this topic,说我需要在mocky.io的HTTP标头中添加Access-Control-Allow-Origin : *。我这样做但它什么都没改变:

enter image description here

以下是新的mocky.io网址:

http://www.mocky.io/v2/5a083d8e2f0000c61ee61140

有谁看到我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

好的,我们在本地访问HTML文件时似乎忽略了Access-Control-Allow-Origin : *(来自file:///C:/.../index.html)。

要使其正常工作,我们必须安装本地服务器(例如,使用this Chrome extension)并通过HTTP(http://127.0.0.1:8887/index.html)访问HTML文件。

或者使用this other Chrome extension自动在HTTP响应的标头中添加Access-Control-Allow-Origin : *

相关问题