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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With