1

I know this error has been posted on this site before, and I've been able to resolve the error, but I'm looking for some explanation on what I've actually done.

So as a learning project I am creating a Wikipedia Viewer, and the first thing I tried to do was to make a call to the Wikipedia API:

$(document).ready(function() {

  var wiki = "https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json"

  $.getJSON(wiki, function(d) {
    console.log(d);
  });

});

This returns an error of XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://conn3cted.uk.tn' is therefore not allowed access.

I was able to stop this error appearing by adding &callback=? onto the end of the GET request (https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json&callback=?)

But I don't fully understand what callback=? is doing, which would stop it erroring?

Edit: This is different to the question linked, as I'm not asking about JSONP (I don't think?) and that questions is centered about using <script> tags, whereas I am asking why adding callback=? made this work.

grpcMe
  • 1,367
  • 5
  • 15
  • 28

1 Answers1

1

Sticking callback=? on the end of the URL causes jQuery to generate a <script> element and make a JSONP request instead of using XMLHttpRequest.

Answers to this question explain how JSONP hacks around the same origin policy.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ah ok - So `callback=?` turns the request into JSONP, which the API accepts? Without this, it fails because it's cross-domain? Is there anything that could be added to my Javascript file, to make this work without the `callback=?` parameter? – grpcMe May 05 '16 at 12:13
  • That's what I said. That's what the error message you quoted says. No, it would be stupid if browsers let your JavaScript bypass security designed specifically to limit what your JavaScript can do. – Quentin May 05 '16 at 12:16
  • I see - thank you for explaining. It seems a little strange that the Wikipedia API documentation, wouldn't mention that you need to have this parameter in your GET request to make it work. I wasn't sure if the 'proper' thing to do would be to set a header somehow and negate the need for `callback=?` – grpcMe May 05 '16 at 12:31