2017-02-06 36 views
2

试图接收来自维基百科API在Codepen上的回应。答复应该是一个JSON,我试图console.log。访问控制允许来源与维基百科API与Jav​​ascript

在控制台然而,我看到了一个错误:

跨来源请求阻止:同源策略不允许在https://en.wikipedia.org/w/api.php?action=opensearch&search=earth&format=json读取远程资源。 (原因:缺少CORS头'Access-Control-Allow-Origin')。

我读过不少关于以上CORS和允许来源这几天试着去了解,但出于某种原因,即使我想我明白......我不能设法实现:)

然而,最有趣的是 - 即使控制台显示这样的错误消息,如果我看看开发人员工具“网络”选项卡中的实际响应,我会看到json响应的所有荣耀!

这将是很好的解释如何可能?

Codepen链接here

var xhrObject = new XMLHttpRequest(); 

xhrObject.onreadystatechange = function() { 
    if (xhrObject.readyState === 4 && xhrObject.status === 200) { 
     console.log(xhrObject.responseText); 
    } 
}; 

xhrObject.open(
    "POST", "https://en.wikipedia.org/w/api.php?action=opensearch&search=earth&format=json", true 
); 
xhrObject.send(); 

在此先感谢

回答

1

origin=*添加到您正在使用的维基百科URL的查询参数中,该请求将起作用。

为了使JavaScript撷取/ XHR请求维基百科的API的工作,你必须在URL中包含查询参数,每the CORS-related docs for the Wikipedia backendorigin=*

For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.

所以问题的URL应该是这样的:

"https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=earth&format=json" 

...甚至是这样的:

"https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=earth=" 

(也就是说,我认为你可以省略format=json,因为JSON输出似乎是默认设置。)

2

However, the most interesting thing is this - even though console shows such an error message if I look at the actual response in developer tools Network tab, I see the json response in all its glory!

It would be great to have an explanation how is that possible?

同源策略的要点是防止Mallary(恶意网站的作者)使用Alice的网络浏览器(其有爱丽丝的饼干和爱丽丝的IP地址和各种其他信息,将其标识为爱丽丝的浏览器)读取鲍勃网站的秘密数据(可能是爱丽丝的网上银行或公司内联网)。

Mallary的JavaScript不允许访问数据,除非Bob告诉Alice的浏览器让JS读取它是安全的(使用CORS)。

Alice的浏览器被允许访问数据,因为Bob已经信任Alice的数据。 Mallary无法访问Alice的浏览器中的开发人员工具。

+0

所以Wiki API信任我的浏览器,但是我无法从Codepen访问它,因为它尚未被批准? 这是怎么做的,通过添加请求标头什么域? Codepens或维基? – KarmaKing

+1

维基百科必须这样做。如果你能够给予你许可,那将是愚蠢的。 – Quentin

相关问题