维基百科API +跨域请求

Pie*_*rre 17 javascript wikipedia-api cors

我正在尝试使用javascript + CORS访问维基百科

据我所知,维基百科应该支持CORS:http://www.mediawiki.org/wiki/API :Cross-site_requests

我尝试了以下脚本:创建XMLHttpRequest + credential/XDomainRequest,添加一些Http-Headers("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();
        }
    };
Run Code Online (Sandbox Code Playgroud)

但我的脚本失败了('xhr.onerror'被调用).我该如何解决?

谢谢.

Ash*_*gan 75

我在使用freeCodeCamp项目时遇到了同样的问题,解决方案很简单,因为我花了几个小时搜索它,所以我笑了.在你的jquery网址中包含以下参数.

&起源=*

工作Codepen

$.getJSON(
  'https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search' +
  '&origin=*' + // <-- this is the magic ingredient!
  '&gsrsearch='q, function(data){ /* ... */ }
);
Run Code Online (Sandbox Code Playgroud)

  • 哟,谢谢!我正在使用相同的项目,并且在使用Wiki API的CORS方面处于困境.出于某种原因,当我读到这个:"MediaWiki API还要求将原点作为请求参数提供"我没有意识到我必须像你指出的那样做.这似乎有点奇怪,虽然它不是托管通常设置allow标头的请求文件的网站?如:Access-Control-Allow-Origin:<origin> |* (3认同)
  • 谢谢!我把头发拉了出来.我昨天能够使用API​​,今天我一直在解决交叉问题.添加这个允许我的请求再次工作. (3认同)

Ade*_*qui 15

截至今天,维基百科通过使用正常的ajax请求(不需要JSONP /回调操作)来支持CORS请求.这可以通过在API调用中设置原点来完成.

对于经过身份验证的请求,它必须与Origin标头中的一个"origin"完全匹配(您需要在进行ajax调用时使用beforeSend属性设置此项).
对于未经身份验证的请求,您只需将其设置为星号(*),并且在使用域中的简单$ .getJSON时它可以正常工作.示例api调用:
https://en.wikipedia.org//w/api.php?action=opensearch&format=json&origin=*&search=stack&limit=10
MediaWiki API沙箱中的更多内容:MediaWiki API沙箱

  • 如果您在浏览器中执行此示例,则该示例只能在没有源的情况下工作,而如果您使用 AJAX 执行此示例,则无效。 (2认同)

Dan*_* W. 11

CORS标头被发送给ALLOW请求脚本以访问内容.

维基百科正在发送CORS,而不是你.

从您链接的页面:

MediaWiki API还要求将原点作为请求参数提供,该参数适当地命名为"origin",它与CORS协议所需Origin头匹配.请注意,此标头必须包含在任何飞行前请求中,因此即使对于POST请求,也应包含在请求URI的查询字符串部分中.

如果CORS原始检查通过,MediaWiki将在响应中包含Access-Control-Allow-Credentials:true标头,因此可以发送身份验证cookie.

这意味着你必须发送一个origin标题来告诉维基百科你来自哪里.维基百科正在管理访问,而不是你.

发送此原始标题:

xhr.setRequestHeader("Origin", "http://www.yourpage.com");
Run Code Online (Sandbox Code Playgroud)

Origin标头是响应标头,而不是请求标头.

维基百科还需要内容类型json:

xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
Run Code Online (Sandbox Code Playgroud)

  • 请注意以上内容:"应该包含在请求URI的查询字符串部分中".因此您无法设置标题,您必须将'&origin =*添加到实际网址. (6认同)

小智 5

你可以使用jQuery JSONP:

$.ajax( {
    url: "https://en.wikipedia.org/w/api.php",
    jsonp: "callback", 
    dataType: 'jsonp', 
    data: { 
        action: "query", 
        list: "search", 
        srsearch: "javascript", 
        format: "json" 
    },
    xhrFields: { withCredentials: true },
    success: function(response) { ... }
}
Run Code Online (Sandbox Code Playgroud)