Random Quote Generator: Can't make JSON work with API


#1

I’ve been trying for 6 hours, tried different APIs and even checked the posts on this forum, my code is pretty much exactly the same as other people’s but still does not work. Here’s my pen https://codepen.io/czonios/pen/zzXNOx

I checked with console.log on my computer and the string that’s supposed to get the quote from JSON remains empty.

Please help me resolve this so I can move on.


#2

Edit: accidentally removed my previous message


#3

Thank you for your answer, however it still doesn’t seem to work.

Also, where can I see the console output in codepen?


#4

I found the console, but still no luck getting quotes.


#5

Awww. I accidentally edited my previous message. Replace your code with this code, and you’ll be ready to move on, just play around with the styling I am on my laptop, and it’s not very comfortable to deal with such a huge window on my 13’’ screen.

 $.getJSON("https://cors-anywhere.herokuapp.com/http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(q) {
          
            console.log(q[0].title);
            var quote = q[0].content;
            var author = q[0].title;
            newQuote += "<h1>\"" + quote + "\"</h1><br><p>- " + author + "</p>";
          $("#quote").html(newQuote);
            });
         
        
    });
});

#6

Thank you, I actually changed the https to http on my own. Now I get the content but I need to get rid of

and stuff, which I think I can handle. Thanks a ton. Can you explain to me what cors-anywhere is and why I needed it? Is it just to make an http link into https?


#7

I am not sure I can tell you why it’s necessary and why we need it. I’ll try my best, but I may be wrong, so don’t fully rely on my explanation.

Whenever you try to use APIs that use HTTP, Chrome and perhaps other browsers are blocking (http?) requests cos of security reasons. By using the special server you’re allowed to get that information you need from the API.

Try removing the server from your code and open your console on the browser you’re using, and you’ll see a very specific error. If you want to know more information, the best thing you can do is google it.


#8

Yeah that’s what I figured, I saw http working on other pens though, that’s weird.

I got it to work. Thanks a lot.


#9

Glad to help you! Have fun coding.


#10

The proxy that @N4thyra recommended is not needed. Just use HTTPS:

https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=

That proxy server is a demo server for showing off the cors-anywhere open source software, and fortunately, not something we need to rely on for any of the APIs we use at Free Code Camp.