Reputation: 127
I'm trying to get quotes from the this website using this code with a GET httprequest
var jsonObj;
var httpReq = new XMLHttpRequest();
var processJson = function (json)
{
jsonObj = JSON.parse(json);
document.getElementById("quote-text").innerHTML = jsonObj.quoteText;
document.getElementById("quote-author").innerHTML = jsonObj.quoteAuthor;
}
httpReq.onload = function()
{
if (httpReq.status === 200)
{
processJson(this.response);
}
};
httpReq.open("GET", "http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", true);
httpReq.send();
The only thing is that this piece of code only works with a CORS plugin installed on Chrome, otherwise it won't work. The error it gives me is the following:
MLHttpRequest cannot load http://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 'http://127.0.0.1:64290' is therefore not allowed access.
Any clue? Thank you!
Upvotes: 0
Views: 440
Reputation: 37975
They clearly don't know what CORS is if they are using JSONP.
JSONP is a format when you include a script with a callback, the risk then is that data can leak and they can insert any code into your page
var loadJSONP = (function(){
var unique = 0;
return function(url, callback, context) {
// INIT
var name = "_jsonp_" + unique++;
if (url.match(/\?/)) url += "&jsonp="+name;
else url += "?callback="+name;
// Create script
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Setup handler
window[name] = function(data){
callback.call((context || window), data);
document.getElementsByTagName('head')[0].removeChild(script);
script = null;
delete window[name];
};
// Load JSON
document.getElementsByTagName('head')[0].appendChild(script);
};
})();
loadJSONP(
'http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en',
function(data) {
console.log(data);
}
);
Another possible solution is to use something like a cors proxy - there are a few out there but you could build your own
var cors = "https://cors-anywhere.herokuapp.com/"
var url = "http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en"
fetch(cors + url)
.then(res => res.json())
.then(json => console.log(json))
The risk with a cors proxy is that they can spy on data that are passing through. You also depend on a extra service that could go down anytime
Upvotes: 1