I want to get json data from API, but it seems not working. I think code will talk by itself
var URL = 'https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';
getData(URL);
function getData(source){
xhr = new XMLHttpRequest();
xhr.onload = function(){
if(xhr.status === 200){
data = JSON.parse(xhr.responseText);
console.log(data);
}
}
xhr.open('GET', source, true);
xhr.send(null);
}
This code gives console Error Failed to load https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have suspicious that it might be CORS, but I have no idea how to fix it.
</div>
You could use: https://cors-anywhere.herokuapp.com/ service, by prepending your URL:
https://cors-anywhere.herokuapp.com/
https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en
You must consider that it is a free service that may not be 100% available.
This API enables cross-origin requests to anywhere.
Something like this:
var URL = 'https://cors-anywhere.herokuapp.com/https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';
getData(URL);
function getData(source) {
xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
data = xhr.responseText;
console.log(data);
}
}
xhr.open('GET', source, true);
xhr.send(null);
}
</div>