2

This API request does not get anything other than a status code of '0' and I cant figure out whats wrong with it. The console.log on the browser reads "response for preflight is invalid (redirect)" but if I simply add the website url to my browser I can access it. There must be something wrong with the way I am making my request but I can't figure it out. Here is the code.

var authKey = "http://en.wikipedia.org/w/api.php?action=centralauthtoken&format=json";
  
  var xhr = new XMLHttpRequest();
 
  xhr.open("GET", authKey, true);
  xhr.setRequestHeader('Api-User-Agent', 'http://s.codepen.io');
  xhr.send();    
  var xmlDocument = xhr.response;
  console.log(xhr.status);
  console.log(xhr.statusText);

I've also changed 'http' to 'https' but I still get '0' only this time on the console you see "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access."

I'm unsure if its the syntax, the way I have structured the request or what but after two days of trying different solutions on stackoverflow and google I've still gotten nowhere. Incase anyone wants to see the actual website i'm having difficulty with its on here http://codepen.io/Ramins01/pen/rxExKw

  • Do you plan to need a centralauth token? It's only necessary if you're planning to do something with the API that requires authentication (like editing). – slaporte Feb 24 '16 at 06:08

1 Answers1

2

An XMLHttpRequest is limited by the same-origin policy. There are a few different ways to get data from another domain, though. The easiest in this case is probably to use JSONP with jQuery. The Wikipedia API supports JSONP.

Here is an example Wikipedia opensearch query with JSONP: http://codepen.io/slaporte/pen/ZQgjQj

var search_term = 'Coffee';
var api_url = "https://en.wikipedia.org/w/api.php";

$.ajax({url: api_url,
        dataType: 'jsonp',
        jsonp: 'callback',
        data: {action: 'opensearch',
               search: search_term,
               limit: 5,
               format: 'json'},
        success: function(response) {

          // Now you have search results!
          console.log(response);

        }
});
Community
  • 1
  • 1
slaporte
  • 703
  • 6
  • 14