Wikipedia Viewer - CORS HELP!

Wikipedia Viewer - CORS HELP!
0

#1

Hi All,

I need your help please. I’ve been struggling for a week now trying to figure out by my self how to solve but I raise the white flag.

I have two issues:

  1. Preflight request not passing the access control test

  2. If the first one is successful, I don’t know how to handle the response using a callback function.

Below is my code & the returned error in the console:

$(document).ready(function () {

    var $keyWord = $("#searchKeyWord").val();

    $(".btn").on("click", function () {
        var apiCall = $.ajax({
            url: 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&origin=*&search=' + $keyWord,
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            dataType: 'json',
            headers: {'Access-Control-Allow-Origin': 'http://localhost:3000'},
            success: handleData,
        });
    });

    function handleData(data) {
        console.log(data);
    };
})

Thanks a lot for your help


#2

https://forum.freecodecamp.org/search?q=No%20'Access-Control-Allow-Origin


#3

Hey,

my confusion about this was about setting the origin. I spent a lot of time digging through docs and jQuery source trying to figure out why I could make it work with jQuery.ajax() and not a vanilla XMLHttpRequest. So, wikiMedia API allows cross-domain requests, you just have to send the request in the correct manner. The API is expecting an ‘origin’ request parameter, not CORS headers. If you append ‘origin=*’ to the query URL that should do it.

Example with jQuery:

someElement.addEventListener('click', function() {
  var requestParams = {
    ...
    format: 'json',
    origin: '*',
    ...
  };
  $.ajax({
    ...
    data: requestParams, 
   ...
  });
});

and as an XMLHttpRequest:

xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  console.log(xhr.responseText);
};
xhr.open('GET', 'https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json&formatversion=2&origin=*');
xhr.send();