We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have a local server running which takes a RESTful request and returns a block of JSON code. I've tested it in my browser, e.g. using a URL like:
http://localhost:8080/api/details/US7222075B2
and it dutifully responds with a block of JSON data. So far so good.
But when I run this snippet of code from within my p5 sketch (cribbed from the weather example in http://p5js.org/examples/demos/Hello_P5_Weather.php):
function findPatent() {
var patent_name = input.value();
var url = 'http://localhost:8080/api/details/' + patent_name
loadJSON(url, gotPatent);
};
// callback from loadJSON call
function gotPatent(json) {
console.log(JSON.stringify(json));
}
... the browser throws an error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I was laboring under the misconception that since this was on localhost, then access control would not be a problem. What am I missing?
(I have a related question about the "json" vs "jsonp" argument to loadJSON, but I'll save that for another question.)
Answers
If you're launching the HTML page hosting the p5 sketch from the local file system you'll hit some significant - and well documented - restrictions blocking cross domain requests: the local file system is not the same as localhost and is subject to added restrictions to protect your OS. Some browsers are more permissive - @GoToLoop always suggests Firefox dev edition as it apparently doesn't block...
Try running your sketch page from a local server (generally recommended anyway - as you'll find from a search); though you may still hit cross domain issues. The solution then is to use CORS. JSONP is an accepted hack to get around this issue without using CORS...
It's not apparent but real. And it's not only Firefox Dev Edition, but any browser based on Firefox!
We can achieve almost the same permissiveness on Chrome-based browsers by adding --allow-file-access-from-files to their shortcuts' target.
In my 64-bit SlimJet (Chrome-based) browser, I've got this 1:
"C:\Program Files\Slimjet\slimjet.exe" --allow-file-access-from-files
An old forum thread about loadJSON():
https://forum.Processing.org/two/discussion/14208/jsons-files