维基百科 API + 跨域请求

2023-04-18前端开发问题
63

本文介绍了维基百科 API + 跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 JavaScript 和 CORS 访问维基百科.

I'm trying to access Wikipedia using JavaScript and CORS.

据我所知,维基百科应该支持 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", etc.) 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 headers are sent to allow a requesting script to access the contents.

维基百科发送的是 CORS,而不是 .

Wikipedia is sending the CORS, not you.

根据评论:

维基百科是一般规则的一个例外,它要求您将 origin 参数附加到您请求的 URL.

Wikipedia is an exception to general rule, by requiring you to append an origin parameter to the URL you are requesting.

我认为这背后的原因与缓存有关.我不知道他们使用的是哪种机制,但它可能使他们更容易更好地存储缓存对象并以这种方式构建变体.

I think the reason behind this is related to caching. I don't know what kind of mechanism they are using, but it probably makes it easier and better for them to store a cache object and build variations that way.

MediaWiki API 文档中有关 CORS 的更多信息:

More on CORS from MediaWiki API documentation:

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:响应中的真实标头,所以可能会发送身份验证 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 标头来告诉维基百科你来自哪里.维基百科正在管理访问权限,而不是您.

This means you have to send an 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-* 标头是 response 标头,而不是 request 标头.

Access-Control-Allow-* headers are response headers, not request headers.

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

Wikipedia additionally requires content type json:

xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");

这篇关于维基百科 API + 跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5

CoffeeScript 总是以匿名函数返回
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)...
2024-04-20 前端开发问题
13