Javascript XMLHttpRequest在控制台上工作,但在脚本标记中用作js文件时显示CORS错误
我正在使用JavaScript 这是我的密码Javascript XMLHttpRequest在控制台上工作,但在脚本标记中用作js文件时显示CORS错误,javascript,xmlhttprequest,cors,Javascript,Xmlhttprequest,Cors,我正在使用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)
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表单域的调试器控制台中执行相同操作时,没有错误
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);
没有错误。我在控制台中获取数据。
谁能给我解释一下这里发生了什么事
谢谢。当您将
内容类型
设置为应用程序/json
时,这会触发cors“预飞行”——一个必须由服务器处理的选项请求
在这种情况下,服务器显然不处理OPTIONS请求,这导致响应中没有访问控制allow origin,从而终止请求
无需设置该标头,尤其是在GET请求中(您没有发送任何内容,为什么要指定内容类型??)
通过删除该行
this.xhr.setRequestHeader('Content-Type', 'application/json');
浏览器不会发送飞行前请求,因此API应按预期运行
根据响应的不同,您可能希望使用
overrideMimeType()
方法来覆盖响应mime类型-但是,由于请求在控制台中工作,您可能也不需要它如果其他域不明确允许,浏览器将不允许您域中的代码访问其他域中的内容。我同意。但是,服务器具有接受跨域请求的配置。当代码包含在项目中并从浏览器控制台调用时,我无法理解在调试器控制台中复制和粘贴代码是如何工作的,也无法工作。我还尝试将angular js$http注入浏览器控制台。在这里,当我发出$http.get请求时,我得到的结果没有问题。请求的资源上不存在“Access Control Allow Origin”头错误。表示服务器没有接受跨域请求的配置。谢谢@jaromanda。工作得很有魅力。另外,我恳请您更新关于如何在服务器端处理选项请求的回答简报。如何在服务器端处理选项取决于服务器环境-每个环境都有大量资源解释如何处理CORS飞行前请求-我不打算为您研究所有这些资源