0

I am trying to access an API through CodePen, but I keep getting the following error:

Refused to set unsafe header "Origin"

XMLHttpRequest cannot load forismatic dot com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

I tried adding the headers by setRequestHeader, but still the same error;

Here is my code:

var button = document.getElementById("btn"),
quote = document.getElementById("quote"),
author = document.getElementById("author");

function showQuote() {
var req = new XMLHttpRequest(),
url = "http://api.forismatic.com/api/1.0/";
function reqReadyStateChange() {
if(req.readyState === 4 && req.status === 200) {
  quote.innerHTML = req.responseText;
 }
}

req.open("POST",url);
req.setRequestHeader("Origin","http://s.codepen.io/");
req.setRequestHeader("Access-Control-Allow-Origin","http://s.codepen.io/");
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = reqReadyStateChange;
req.send();

}

button.addEventListener("click", showQuote);
Drenmi
  • 8,492
  • 4
  • 42
  • 51
Javed
  • 460
  • 4
  • 15
  • The server that owns the API needs to allow the cross domain, you cannot force it – Jesse Oct 11 '15 at 05:55
  • Yes, but others have tried and its working for them, take look at this (Codepen) [http://codepen.io/lucasvorsteveld/full/OVeaLZ], its the same API but only with jQuery – Javed Oct 11 '15 at 06:00
  • They're using JSONP, not XHR. Forismatic doesn't support XHR, so you have to use JSONP. e.g. http://stackoverflow.com/questions/21715620/using-jsonp-to-get-json-data-from-another-server Edit: or just look at their pen: http://codepen.io/lucasvorsteveld/pen/OVeaLZ – Daniel Flint Oct 11 '15 at 06:02

1 Answers1

1

Unfortunately the server hosting the API itself is not allowing the connection the way you are doing it.

Here is an example running a simple request directly from the console on this page.

var xhr = new XMLHttpRequest();
xhr.open( 'GET', 'http://api.forismatic.com/api/1.0/', true );
xhr.send()

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access. VM587:2 XHR failed loading: GET "http://api.forismatic.com/api/1.0/".

So in this error message it states that "No 'Access-Control-Allow-Origin' header is present on the requested resource." The resource being the server containing the API. Therefor no access is provided cross domain like this.

You are going to want to look into the answers from this question -> How to make a JSONP request from Javascript without JQuery?

Here they are loading this the way this API (and probably most APIs) prefer. Which appears to be just loading it into a script tag.

Community
  • 1
  • 1
Jesse
  • 2,790
  • 1
  • 20
  • 36