我正在尝试使用JavaScript和CORS访问维基百科。
据我所知,维基百科应该支持CORS:http://www.mediawiki.org/wiki/API:Cross-site_requests
我尝试了以下脚本:创建一个XMLHttpRequest +凭据/XDomainRequest,添加一些HTTP头(“Access-Control-Allow-Credentials”等),并发送查询。
http://jsfiddle.net/lindenb/Vr7RS/
var WikipediaCORS=
{
setMessage:function(msg)
{
var span=document.getElementById("id1");
span.appendChild(document.createTextNode(msg));
},
// Create the XHR object.
createCORSRequest:function(url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr)
{
xhr.open("GET", url, true);
}
else if (typeof XDomainRequest != "undefined")
{
xhr = new XDomainRequest();
xhr.open(method, url);
}
else
{
return null;
}
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
return xhr;
},
init:function()
{
var _this = this;
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=Javascript&format=json';
var xhr = this.createCORSRequest(url);
if (!xhr)
{
this.setMessage('CORS not supported');
return;
}
xhr.onload = function()
{
_this.setMessage(xhr.responseText);
};
xhr.onerror = function()
{
_this.setMessage('Woops, there was an error making the request.');
};
xhr.send();
}
};
但是我的脚本失败了('xhr.onerror'被调用)。我该如何修复它?
拒绝设置不安全的标头“Origin”(index):1 XMLHttpRequest无法加载http://en.wikipedia.org/w/api.php?action=opensearch&search=Javascript&format=json。请求的资源上没有“Access-Control-Allow-Origin”标头。因此,源“http://fiddle.jshell.net”无法访问。
- Ronni Skansing