Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No 'Access-Control-Allow-Origin' header is present. Origin is therefore not allowed access

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

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 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.

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

Code:

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();

Some of the things i've tried:

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");

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

like image 967
Sneb Avatar asked Nov 19 '25 16:11

Sneb


1 Answers

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>

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
})
like image 106
Ming Avatar answered Nov 21 '25 05:11

Ming