"Build a Simple Android App" was retired on September 15, 2017. You are now viewing the recommended replacement.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Retrieving a random sentence from forismatic API error:

Hi there,

As the question states, I am trying to retrieve a random sentence from an API for my project which is a 'Random Quote Generator.'

I am receiving this error:

https://gyazo.com/a9e67b4d542b5a93d282686a4767bf11

Here is my code:

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Random Quote Generator</title>
  <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>

<body>
  <div class="container">
    <h1>Random Quotes Rewritten</h1>
    <p>Would you like a random sentence to send to someone or incorporate in your project? Press the button below!</p>
    <button>New quote</button>
    <div class="quotearea">

    </div>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>

</html>

JS:

$("button").click(function(){
  var URL = "http://api.forismatic.com/api/1.0/";
  var options = {
    method : "getQuote",
    format : "json",
    lang : "en"
  };

  function callback(data) {
    console.log(data);
  }

  $.getJSON(URL, options, callback);
});

It's weird because if I open the URL which I am trying to do a GET from, it works fine in the browser... I just can't seem to use it in my project. What exactly is going wrong?

Thanks, James.

1 Answer

Steven Parker
Steven Parker
243,214 Points

This becomes a CORS request from the page.

You can connect to this resource directly from your browser, but when you do it from JavaScript code it becomes a cross-origin request. And according to the jQuery documentation for getJSON:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

So since this service doesn't send out the necessary headers to allow cross-origin requests access, you would need to consume this API from your server, or through a CORS proxy.