2017-07-27 21 views
0

首先,我是使用API​​的新手。简单的API调用(CORS)不起作用

我正在尝试对不同的域(天气服务)进行最基本的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,我得到这个消息:原产地:头是必需的。在控制台中,它给出了状态码403 - 但我读到只有服务器可以控制/访问标题,而且我(编码器)不能。

+1

您只是在请求发送之前尝试读取状态。你必须等待回应。 – Quentin

+1

“但我读过,只有服务器可以控制/访问标题” - HTTP消息有标题。 HTTP请求具有标题。 HTTP响应具有标题。服务器抱怨你的HTTP请求没有包含“Origin”标头。这是因为您没有使用XMLHttpRequest发送它。 – Quentin

+0

@行2上的Quentin,我将xhr定义为XMLHttpRequest。为什么它不是XMLHttpRequest呢?非常感谢你 – thesystem

回答

1

您正在呼叫xhr.send(),然后立即试图读取响应的状态。

你必须等到有回应,然后才能做到这一点。

使用加载事件侦听器。

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

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