【问题标题】:Simple API call (CORS) not working简单 API 调用 (CORS) 不起作用
【发布时间】:2018-01-03 09:20:51
【问题描述】:

首先,我是使用 API 的新手。

我正在尝试对与我自己的客户端不同的域(天气服务)进行最基本的 API 调用。其中,我遇到了 CORS 问题、没有正确的标头等,因此我尝试通过 crossorigin.me 引导调用来解决问题(从我的代码中的 URL 可以明显看出)。

(这不是代码,而只是问题 - 向下滚动代码)但是,我的代码目前导致...

console.log(status); //returns 0
console.log(statusText); //returns an empty string

这是完整的代码。

function createCORSRequest(method, url) {
  xhr = new XMLHttpRequest();

  //I work in Chrome, so I only included withCredentials, not accounting for other browsers
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  }
  xhr.send();
  console.log(xhr.status); //returns 0
  console.log(xhr.statusText); //returns empty string
}

createCORSRequest("GET", "https://crossorigin.me/https://www.metaweather.com/api/location/2459115");

如果您直接访问该站点,https://crossorigin.me/https://www.metaweather.com/api/location/2459115,我会收到以下消息:Origin: header is required。在控制台中,它给出状态码 403 - 但我读到只有服务器可以控制/访问标头,而我(编码器)不能。

【问题讨论】:

  • 您只是想在请求发送之前读取状态。您必须等待响应。
  • “但我读到只有服务器可以控制/访问标头”——HTTP 消息具有标头。 HTTP 请求具有标头。 HTTP 响应具有标头。服务器抱怨您的 HTTP 请求未包含 Origin 标头。这是因为您没有使用 XMLHttpRequest 发送它。
  • @Quentin 在第 2 行,我将 xhr 定义为 XMLHttpRequest。那么为什么它不是 XMLHttpRequest 呢?非常感谢
  • 您说“如果您直接访问该站点... Origin: header is required”。那你就不用 XMLHttpRequest 了。
  • 啊,当然。非常感谢您的帮助。

标签: javascript api xmlhttprequest cors


【解决方案1】:

您正在调用xhr.send(),然后立即尝试读取响应状态。

您必须等到有响应才能执行此操作。

使用加载事件监听器。

xhr.addEventListener("load", log_status);
xhr.send();

function log_status() {
   console.log(this.status);
   console.log(this.statusText);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2017-03-29
    • 2018-05-22
    相关资源
    最近更新 更多