[英]XMLHttpRequest 'Access-Control-Allow-Origin' Error
I am writing a web-based application where I need to access the txt file that is hosted online and read the file.我正在编写一个基于 Web 的应用程序,我需要在其中访问在线托管的 txt 文件并读取该文件。 I am using following code to do it:
我正在使用以下代码来做到这一点:
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function(){
// parse the file
}
})
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.send();
I got this error:我收到此错误:
Failed to load https://bahadorsaket.com/others/ranking.txt : No 'Access-Control-Allow-Origin' header is present on the requested resource.
无法加载https://bahadorsaket.com/others/ranking.txt :请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access.
因此,不允许访问 Origin 'null'。
After searching and reading this post , I tried changing my code to this.搜索并阅读这篇文章后,我尝试将代码更改为此。
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function(){
// parse the file
}
})
oReq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.send();
This time I got this error:这次我收到了这个错误:
Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
无法在“XMLHttpRequest”上执行“setRequestHeader”:对象的状态必须为 OPENED。
Any idea how to fix this problem?知道如何解决这个问题吗? I am very new to these kinds of stuff!!!
我对这些东西很陌生!!!
Although not the best method, you can use a proxy also.虽然不是最好的方法,但您也可以使用代理。
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
I used this in the past and it worked very well.我过去用过这个,效果很好。
Taken from this post.取自这个帖子。
For the specific error:对于特定错误:
Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
无法在“XMLHttpRequest”上执行“setRequestHeader”:对象的状态必须为 OPENED。
It's because you're setting the header before invoking the open
method on the XMLHttpRequest
object.这是因为您在调用
XMLHttpRequest
对象上的open
方法之前设置了标头。 Reordering to this will fix that specific error:重新排序将修复该特定错误:
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function(){
// parse the file
}
})
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
oReq.send();
But like the others have mentioned, you may then face other issues if the backend server isn't configured to support CORS.但就像其他人提到的那样,如果后端服务器未配置为支持 CORS,您可能会面临其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.