Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
    })
};
like image 565
Franco Javier Danussi Avatar asked Oct 23 '25 21:10

Franco Javier Danussi


1 Answers

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.

like image 105
aaron Avatar answered Oct 26 '25 11:10

aaron