维基百科API +跨域请求 [英] Wikipedia API + Cross-origin requests
问题描述
我尝试使用javascript + CORS 访问维基百科。
I'm trying to access wikipedia using javascript+CORS
据我所知,wikipedia应该支持CORS: http://www.mediawiki .org / wiki / API:Cross-site_requests
As far as I know, wikipedia should support CORS: http://www.mediawiki.org/wiki/API:Cross-site_requests
我尝试了以下脚本:创建XMLHttpRequest + credential / XDomainRequest,添加一些Http- Access-Control-Allow-Credentials,...)并发送查询。
I tried the following script: create a XMLHttpRequest+credential/XDomainRequest, add some Http-Headers ( "Access-Control-Allow-Credentials",...) and send the query.
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'被调用)。如何解决?
But my script fails ('xhr.onerror' is called). How can I fix it ?
感谢。
推荐答案
CORS标题
维基百科正在发送CORS,而不是您。
Wikipedia is sending the CORS, not YOU.
从您链接的页面:
MediaWiki API还要求将原始码作为
请求参数提供, origin,它通过CORS协议与所需的Origin标头匹配
。请注意,
此标头必须包含在任何预先请求中,因此
也应包含在请求URI的查询字符串部分中,即使对于
POST
The MediaWiki API also requires that the origin be supplied as a request parameter, appropriately named "origin", which is matched against the Origin header required by the CORS protocol. Note that this header must be included in any pre-flight request, and so should be included in the query string portion of the request URI even for POST requests.
如果CORS原始检查通过, MediaWiki将在响应中包含
Access-Control-Allow-Credentials:true标头,因此可能会发送
身份验证Cookie。
If the CORS origin check passes, MediaWiki will include the Access-Control-Allow-Credentials: true header in the response, so authentication cookies may be sent.
这意味着您必须发送 Origin
标题来告诉wikipedia你从哪里来。
This means you have to send a Origin
header to tell wikipedia where you are coming from. Wikipedia is managing the access, not you.
发送此来源标题:
xhr.setRequestHeader("Origin", "http://www.yourpage.com");
Access-Control-Allow - *
标头。
Wikipedia另外还需要json内容类型:
Wikipedia additionally requires content type json:
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
这篇关于维基百科API +跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!