javascript - 调用 REST API、JavaScript 时的 CORS 策略
问题描述
我正在尝试在 JavaScript 中调用 API,如果我在 URL 栏中编写它,它可以工作,但如果我使用我的代码,它有 CORS 策略问题。我无权访问服务器,我应该找到一种在客户端解决的方法。这是我的代码:
var xhr = new XMLHttpRequest();
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-Key';
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader("APPID", "MY API Key");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Origin', '*');
//console.log(json);
xhr.send();
xhr.onload = function () {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
alert(`Done, got ${xhr.response.length} bytes`);
}
};
xhr.onprogress = function (event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function () {
alert("Request failed");
};
</script>
它有错误:
从源“ https://localhost:44399 ”访问位于“ https://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-key ”的 XMLHttpRequest已被 CORS 策略阻止:响应预检请求未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
任何人有想法如何解决这个错误?我应该将我的 Origin 或其他任何内容作为标头发送到哪里才能从服务器获得正确的响应?我应该在客户端处理它,并且我已经在标题中写了 Origin * 但仍然无法正常工作。
此致
解决方案
您是否尝试在服务器上使用“allow-origin: *”标头?这可能是问题的原因(您的服务器不接受这些请求)
推荐阅读
- angular - 生产构建中的 Angular 和 Ionic 应用程序问题
- c# - 使用自定义控件排序列表
- c# - 是否可以创建基础 EF DbContext 并在许多服务中使用它?
- c# - editorConfig 命名约定不起作用 c# visual studio 2019 16.4.2
- angular - 角度材料分页未按预期工作
- flutter - 颤振简单的选框小部件并使 ScrollController 未附加到任何滚动视图错误
- php - 如何以特定模式打印数字?
- php - 如何修复 MessageFormatter 返回格式不正确的日期?
- virtual-machine - 通过 Softlayer API 创建 IBM VM 需要更长的时间
- css - Angular FlexLayout 将所有设备的选择元素和 fab-mini 对齐在同一行,但在边界上未对齐