不存在“Access-Control-Allow-Origin”报头。因此原产地不允许进入 [英] No 'Access-Control-Allow-Origin' header is present. Origin is therefore not allowed access

查看:947
本文介绍了不存在“Access-Control-Allow-Origin”报头。因此原产地不允许进入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:没有JSONP!是的,我知道CORS由服务器处理,是的服务器支持它。这个问题在我身上。

No JSONP! Yes i know CORS is handled by the server and Yes the server does support it. The issue is on my side.

我想从浏览器中使用MediaWiki API。我通过XMLHttpRequest发送一个GET请求,但由于CORS问题,它只是不工作。在收到响应后,我的浏览器收到以下消息:

I am trying to use MediaWiki API from the browser. I am sending a GET request through XMLHttpRequest but due to CORS issues it's just not working. I am getting the following message from my browser after it receives the response:


XMLHttpRequest无法加载 https://en.wikipedia.org/w/api.php ?format = json& action = query& list = search& srsearch = Oculus& utf8 。在所请求的资源上没有Access-Control-Allow-Origin头。原因 http://127.0.0.1:8000 因此不允许访问。

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=Oculus&utf8. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access.

我明白为什么我得到这个问题,但我不知道如何从浏览器/ JavaScript端解决它。

I understand why i am getting this issue but i do not know how can i solve it from the browser/JavaScript side.

代码:

xmlhttp.open("GET","https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=" + subreddit + "&utf8",true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xmlhttp.send();

我尝试过的一些事情:

xmlhttp.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost');
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
xmlhttp.setRequestHeader('Access-Control-Allow-Credentials', true)
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");

并在url中设置参数origin或setRequestHeader,返回一个无效的/无效的Origin,被拒绝。

and setting the parameter origin in the url or as setRequestHeader which returned a invalid/bad Origin, denied.

推荐答案

您可以使用JSONP。

You can use JSONP.

<script src='https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=Oculus&utf8&callback=callbackname'></script>
<script>
    function callbackname(data){
       //you can get response data here
    }
</script>

如果使用jquery。

If you use jquery.

$.getJSON('https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=Oculus&utf8&callback=?', function(data){
    //you can get response data here
})

这篇关于不存在“Access-Control-Allow-Origin”报头。因此原产地不允许进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆