Search code examples
javascriptajaxapixmlhttprequest

Why if this API gives the "No Access-Control-Allow-Origin header", can I access it through the address bar or http://www.hurl.it


EDIT: See: https://softwareengineering.stackexchange.com/questions/216605/how-do-web-servers-enforce-the-same-origin-policy for a great explanation on why browsers enforce Access-Origin restrictions but servers (like Hurl.It) are not restricted.

I'm trying to use the API found here http://forismatic.com/en/api/. But I am getting the "No 'Access-Control-Allow-Origin' header" error. If that is the case, why can I access the API by entering the URL with its parameters directly into the address bar of my browser, or through http://www.hurl.it ? I am using codepen if that affects anything.

My code is below. Thank you very much, I've been searching around for a few hours but I'm at a dead end.

var quoteRequest =  new XMLHttpRequest();

quoteRequest.open("GET", "http://www.api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", true);

quoteRequest.send();

var quote = JSON.parse(quoteRequest.responseText);

Solution

  • If that is the case, why can I access the API by entering the URL with its parameters directly into the address bar of my browser, or through http://www.hurl.it ?

    Because that's how the Same Origin Policy works: It applies to ajax requests, not direct requests (typing it in to the address bar) or server-side requests (what Hurl-It does).

    The purpose of the SOP is to prevent Page A using Page B's resources within Page A, from within the browser. This is primarily to protect the user, since when the browser requests resources from Page B, it may use the user's session or other credentials, revealing information to Page A's code that it should have access to. apsillers has a great explanation of this over on programmers.stackexchange.com; here's an excerpt:

    For example, suppose I accidentally load http://evil.com/, which sends a request for http://mail.google.com/. If the SOP were not in place, and I was signed into Gmail, the script at evil.com could see my inbox. If the site at evil.com wants to load mail.google.com without my cookies, it can just use a proxy server; the public contents of mail.google.com are not a secret (but the contents of mail.google.com when accessed with my cookies are a secret).

    If that API doesn't grant access to your origin (your page), and doesn't offer a JSONP alternative, you can only use it indirectly, via a server in the middle (your own server, or Hurl-It, etc.).