问题描述
试图从Codepen上的Wikipedia API接收响应.回复应该是我正在尝试console.log的json.
Trying to receive a response from the Wikipedia API on Codepen. The reply should be a json which i'm trying to console.log.
但是在控制台中,我看到一个错误:
In the console however I see an error:
跨域请求被阻止:同源起源"策略不允许在 https://en.wikipedia.org/w/api.php?action=opensearch&search=earth&format=json . (原因:CORS标头"Access-Control-Allow-Origin"缺失).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://en.wikipedia.org/w/api.php?action=opensearch&search=earth&format=json. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
过去几天,我已经读了很多有关CORS和Allow-Origin的文章,试图理解,但是由于某些原因,即使我认为我理解...我也无法实现:)
I've read quite a bit over the past few days about CORS and Allow-Origin to try to understand but for some reason even when I think I understand... I cannot manage to implement :)
然而,最有趣的是-即使控制台显示这样的错误消息,如果我在开发人员工具网络"标签中查看实际响应,我也会看到json响应的全部荣耀!
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?
Codepen链接此处
Codepen link 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();
预先感谢
推荐答案
将origin=*
添加到正在使用的Wikipedia URL的查询参数中,该请求将起作用.
Add origin=*
to the query params of the Wikipedia URL you’re using, and the request will work.
要使对Wikipedia API的JavaScript Fetch/XHR请求正常工作,您必须在URL查询参数中包含origin=*
,每个 Wikipedia后端的CORS相关文档:
To make JavaScript Fetch/XHR requests to the Wikipedia API work, you must include origin=*
in the URL query params—per the CORS-related docs for the Wikipedia backend:
所以问题中的URL应该是这样的:
So the URL in the question should be like this:
"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输出似乎是默认的.)
(That is, I think you can omit format=json
because JSON output seems to be the default.)
这篇关于具有Wikipedia API和Javascript的Access-Control-Allow-Origin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!