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);