我正在尝试从前端访问 API,并且我尝试了 xhr 和 fetch api 请求。
使用 fetch 时,我收到错误“对预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。来源' http://127.0.0.1:5500 ' 因此不允许访问。如果不透明的响应满足您的需求,请将请求的模式设置为 'no-cors' 以获取禁用 CORS 的资源。
但是,在使用 XHR 时,我没有收到 headers not present 警告,它成功地从 api 获取 JSON。
我不太了解 CORS,但我的理解是我请求的 api 上没有标头,因此无法获取 API。但是,xhr 是如何在 API 上假定缺少标头的情况下获取 api 的?XMLHTTPRequest 中的请求如何可能而不是 fetch 请求中的请求?我将如何使用 fetch 来获取此 API?我在下面包含了我的 fetch 和 XHR 代码以供参考。
获取代码:
fetch(requestURL, {
headers: {
"Content-Type": "application/json",
'Authorisation': 'Basic' + apiKeySecured,
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": false,
"api-key": apiKeySecured,
}
}).then(function (response) {
return response.json();
})
.then(function (myJson) {
console.log(JSON.stringify(myJson));
})
.catch(error => console.error(error));
XHR 代码:
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", requestURL);
xhr.setRequestHeader(`api-key`, apiKeySecured);
xhr.send();