Wikipedia viewer in plain Js

Wikipedia viewer in plain Js
0.0 0

#1

Hi!
I’ve a problem with my pen. The url of the call is correct but I don’t see the data in the console.
Help me to understand why please:)
I would like to use JavaScript and no jQuery.
Here’s my pen.

thanks a lot;

Irene


#2

You are nearly there! Change your url to:

var url = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=" + query + "&origin=*";

Notice the &origin=* at the end. This is due to CORS headers. Its a somewhat complicated concept but its basically what a server uses when controlling who can call its endpoints.

I like your approach of using just JS and no jQuery. Have a look into fetch for calling apis. Its supported in most modern browsers now. Its a bit more straightforward than XMLHttpRequest.


#3

Look at your browser’s console (Ctrl+Shft+J in Chrome) and you will see the reason why it does not work.

In your url string variable replace &callback=? with &origin=*

This will allow you to see something, but then you will have to deal with a different issue related to the fact that data is not an array, but instead is an object, so the forEach method is not valid.


#4

Thanks a lot! I saw the error in console. Now it works!
A last question: adding &origin=* at the end is good only for this API or in general for others?
Thanks!:slight_smile:


#5

Thanks:) Yes I can’t use forEach, now I’m studying the correct loop for this.
Thanks a lot!