XMLHttpRequest help


Hi all…

I’m working on Wikipedia Viewer and I’m making XMLHttpRequest to get data from Wikipedia API, but I’m getting this error:

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=opensearch&search=donald%20trump&format=json&callback=?. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

Could someone explain to me how to set header and what it should look like and why?

I know that it would probably be easier to use jQuery for this but I want to make this with pure JS if possible.



You are getting a CORS error, which is fairly common when working with APIs.

For read-only access to Wikipedia through their API, you can specify origin=* in your API URL.


This way, there’s no need to use JSONP or a cross origin proxy to work around the cross origin errors. For some details on this parameter, see the Wikipedia API Sandbox: https://en.wikipedia.org/wiki/Special:ApiSandbox

Another example of using origin=* is also discussed in this Stack Overflow answer: https://stackoverflow.com/a/38921370


Thank you for the answer and the links!


Thanks, @SkyC.
I now found the mention in the APISandbox.

When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain. This must be included in any pre-flight request, and therefore must be part of the request URI (not the POST body).

For authenticated requests, this must match one of the origins in the Origin header exactly, so it has to be set to something like https://en.wikipedia.org or https://meta.wikimedia.org. If this parameter does not match the Origin header, a 403 response will be returned. If this parameter matches the Origin header and the origin is whitelisted, the Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers will be set.

For non-authenticated requests, specify the value *. This will cause the Access-Control-Allow-Origin header to be set, but Access-Control-Allow-Credentials will be false and all user-specific data will be restricted.