首先,我是 API 的新手。
我正在尝试对与我自己的客户端不同的域(天气服务)进行最基本的 API 调用。其中,我遇到了 CORS 问题,没有正确的 header 等等,所以我尝试通过 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 - 但我读到只有服务器可以控制/访问 header ,而我(编码器)不能。
最佳答案
您正在调用 xhr.send()
,然后立即尝试读取响应的状态。
您必须等到有响应才能执行此操作。
使用加载事件监听器。
xhr.addEventListener("load", log_status);
xhr.send();
function log_status() {
console.log(this.status);
console.log(this.statusText);
}
关于javascript - 简单的 API 调用 (CORS) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45354283/