I must write a code which will take info from Wikipedia, and I wrote this:
function getInfo() {
let search = "Teatr Wielki";
fetch("https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=" + search + "&limit=5", {
headers: {
'Accept': 'application/json',
},
}).then(response => response.json())
.then(addInfo)
.catch (e => requestError(e));
function addInfo(data) {
console.log(data);
const info = data.results[3][1];
if (info) {
document.querySelector('#results').innerHTML = info;
} else {
document.querySelector('#results').innerHTML = 'Unfortunately, no info was returned for this data.'
}
}
function requestError(e, part) {
console.log(e);
document.querySelector('#results').innerHTML = '<br>Oh no! There was an error making a request for this place';
}
}
But this code returns an error:
TypeError: Cannot read property '3' of undefined at addInfo.
I tried to used many options, for example: only [0], only [1] - but nothing is working. Maybe some of you know what is wrong in my code?
Data returned from the wikipedia (mediawiki) api does not have the results
key. The response from the server is a single array.
So, to fetch result, in your code, you must supress the results
key and access directly the data object:
const info = data[3][1];
Your working code: https://jsfiddle.net/mrlew/cq73byu8/