【问题标题】:How to make a CORS Request with Javascript [duplicate]如何使用 Javascript 发出 CORS 请求 [重复]
【发布时间】:2015-03-02 11:54:23
【问题描述】:

我正在尝试编写一个代码,该代码可以根据其他服务器上提供的信息自动填写表格。准确地说:http://services.runescape.com/m=hiscore/index_lite.ws?player=playername

这是我的代码:

var name = document.form.name.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    alert(xmlhttp.responseXML);
}
xmlhttp.open("GET","http://services.runescape.com/m=hiscore/index_lite.ws?player="+name,true);
xmlhttp.send();

但是 Firefox 总是显示这个错误:

跨域请求被阻止:同源策略禁止读取http://services.runescape.com/m=hiscore/index_lite.ws?player=drumgun上的外部资源。这可以通过移动重新来解决 源到同一个域或激活 CORS。

可能有一些语法错误,因为我是从德语翻译过来的。

然后我尝试使用 Firefox 使用的相同标头:

var name = document.form.name.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    alert(xmlhttp.responseXML);
}
xmlhttp.open("GET","http://services.runescape.com/m=hiscore/index_lite.ws?player="+name,true);
xmlhttp.setRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
xmlhttp.setRequestHeader("Host","services.runescape.com");
xmlhttp.setRequestHeader("DNT","1");
xmlhttp.setRequestHeader("Connection","keep-alive");
xmlhttp.setRequestHeader("Accept-Language","de,en-US;q=0.7,en;q=0.3");
xmlhttp.setRequestHeader("Accept-Encoding","gzip,deflate");
xmlhttp.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
xmlhttp.send();

但是发生了同样的错误..希望你能帮助我。

【问题讨论】:

  • 客户端无能为力,CORS 必须在服务器上启用,而不是在客户端浏览器中
  • 真的吗?我知道使用该网站信息的网站。标题可能是问题吗?或者如果他们使用其他东西会有所不同吗?像PHP?不过感谢您的回复

标签: javascript http-headers cors


【解决方案1】:

XlmHttpRequest 仅在启用跨域资源共享 (CORS) 的情况下才能跨域工作。如果您可以控制服务器,您可以通过以下方式启用它:http://enable-cors.org/server.html

如果您无法控制服务器,那么您就不走运了。如果它们支持 JSONP,您也许可以通过普通脚本获取信息。

第三种选择(再次需要您自己的服务器)是在您自己的域上设置一个代理,然后它会为您获取相关数据。由于只有浏览器受 CORS 限制,您可以在服务器上使用您最喜欢的编程语言获取数据并传递它

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 2019-01-24
    • 2017-04-14
    • 2017-05-31
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2021-02-16
    相关资源
    最近更新 更多