Franco Javier Danussi
Franco Javier Danussi

Reputation: 43

Using fetch library for Wikipedia API - Javascript

I'm developing a Wikipedia Viewer and I'm trying to extract some data from the Wikipedia API. This is supposed to be a normal request, any idea why this method is not giving any response? I'm using fetch library. The line console.log(data) doesn't run at all.

function getArticleList() {
    var searchFor = "";
    searchFor = document.getElementById('intext').value;
    console.log(searchFor);
    fetch("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchFor + "&limit=5").then(function(resp) {
        console.log("trySearch");
        return resp.json()
    }).then(function(data) {
        console.log(data);
        document.querySelector.artName.innerText = data.object[1];
        document.querySelector.textArt.innerText = data.object[0];
        document.querySelector.href = data.object[2]
    })
};

Upvotes: 4

Views: 5919

Answers (2)

aaron
aaron

Reputation: 351

From Wikimedia's documentation: 'For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.'

The following worked for me:

fetch("https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=Belgium&limit=5").then(function(resp) {
    console.log(resp);
    return resp.json()
}).then(function(data) {
    console.log(data);

Notice that I filled in my own search with 'Belgium', but your code should work with the right modifications.

Upvotes: 20

Mahad
Mahad

Reputation: 162

Any particular reasons to use fetch library ? This can be done using simple Jquery AJAX.

 function getArticleList() {

 var searchFor = document.getElementById('intext').value;
 var response="";
 console.log(searchFor);
 $.ajax({
    url: "https://en.wikipedia.org/w/api.php?action=opensearch&search="+searchFor+"&limit=5",
    dataType: 'jsonp',
    success: function(data){    
        console.log(data);
        response=data;
    }
}).done(function(response) {
      console.log(response);
      document.querySelector.artName.innerText = response.object[1];
      document.querySelector.textArt.innerText = response.object[0];
      document.querySelector.href = response.object[2];
  });

};

Upvotes: -6

Related Questions