Reputation: 470
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);
Upvotes: 0
Views: 549
Reputation: 2830
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.
Upvotes: 1