我正在使用 JavaScript。
这是我的代码
const BASE_URL = "https://example.com/api";
export class BankApi {
constructor(XMLHttpRequest){
this.xhr = XMLHttpRequest;
}
getBankList(callback){
this.xhr.open("GET", BASE_URL+"/listbanks", true);
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.send(null);
this.xhr.onreadystatechange = function(){
if (this.readyState != 4) return;
if (this.status == 200) {
var data = JSON.parse(this.responseText);
callback(data);
}
};
}
}
我已经用 ES6 编写了代码,但我有使用 Transform-es2015-modules-umd 的 min.js。 我已将此文件包含在客户端项目中
当我打电话时
var bankApi = new BankApi(new XMLHttpRequest());
bankApi.getBankList(function(data){
console.log(data);
})
我收到错误
XMLHttpRequest cannot load https://example.com/api/listbanks.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://engineeringqna.com' is therefore not allowed access.
但是当我从 chrome 形式的调试器控制台 https://engineeringqna.com 执行相同操作时域名没有错误。
var xhr = new XMLHttpRequest();
xhr.open("GET","https://example.com/api/listbanks",true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function(){
if (xhr.readyState == 4)
{
if (xhr.status == 200) {
console.log(data);
}
else {
alert("xhr Errors Occured");
}
}
}
xhr.send(null);
没有错误。我在控制台中获取数据。 谁能解释一下这是怎么回事?
谢谢。
最佳答案
当您将 content-type
设置为 application/json
时,这会触发 cors“预检” - 一个 OPTIONS 请求,必须由服务器处理
在这种情况下,服务器显然不处理 OPTIONS 请求,这会导致响应中没有 access-control-allow-origin,从而终止请求
无需设置该 header ,尤其是在 GET 请求中(您没有发送任何内容,那么为什么要指定内容类型??)
通过删除该行
this.xhr.setRequestHeader('Content-Type', 'application/json');
浏览器不会发送预检请求,因此 API 应按预期运行
根据响应,您可能需要 overrideMimeType()
方法来覆盖响应 mime 类型 - 但是,由于请求在控制台中工作,您可能也不需要这个
关于javascript - XMLHttpRequest 在控制台上工作,但在脚本标记中用作 js 文件时显示 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42354687/