How to make JSONP request in plain JS to avoid CORS error?
From Wikipedia API Main page:
When you make HTTP requests to the MediaWiki web service API, be sure to specify a User-Agent header that properly identifies your client. Don’t use the default User-Agent provided by your client library, but make up a custom header that identifies your script or service and provides some type of means of contacting you (e.g., an e-mail address).
Looks like you need to include xhr.setRequestHeader( 'Api-User-Agent', 'Example/1.0' );
in your getJSON function.
Already tried, not working, same error.
You must use JSONP trick to overcome the XMLHttpRequest same domain policy error.
var url = ‘https://en.wikipedia.org/w/api.php?’ +
‘action=query&list=search&srsearch=’ + text +
’&srwhat=text&utf8=&format=json&callback=’ + callback;
// calback is the name of function which receive data
// like var callback = ‘wikiSearchDataHandler’;
// and define function like:
// function wikiSearchDataHandler(searchObject) { … }
// this is the JSONP trick
var script = document.createElement(‘script’);
script.type = ‘text/javascript’;
script.src = url;
document.head.appendChild(script);