This works from the browser window, but when I try to run it as javascript in the browser, it always returns a status of 0
(Even when I substitute the URL with any another URL for a simple GET request - for e.g. http://www.yahoo.com, I still get the same result.
Here is the code:
(function callRestAPI() {
var request = new XMLHttpRequest();
var url = "http://quotes.stormconsultancy.co.uk/random.json";
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
alert("The response was: " + request.responseText);
} else if (request.status === 0) {
alert("The response was a status code of 0");
}
}
};
request.open("GET", url, "false");
request.send();
})();
I am at a loss on how to figure this out. Any help would be appreciated.
(Note: I get the same result when I run it locally from a file on my computer and also from codepen.io (http://codepen.io/jaytsecan/pen/MeyVjb)
(I am using Firefox 47 and Chrome 51 to test locally)
I’m ony phone right now so can’t test your code. Do you have a server running? Try Python simple server or get http-server from npm
I think that’s how I solved a similar issue before
I tried it with python simple server running. I get the same result (status of 0)
I’m assuming that XMLHttpRequest can be used for any GET request, and most simple GET requests (like getting the page at www.amazon.com) don’t need to have any headers set.
So why won’t it work? I have a feeling there is something wrong with my javascript code (or the way I’m calling it), but can’t figure it out…
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote
resource at http://quotes.stormconsultancy.co.uk/random.json. (Reason:
CORS header ‘Access-Control-Allow-Origin’ missing).
Is there any client-side solution to this? (I know others at FCC have made it work using jQuery, but I haven’t come across a working solution ini JavaScript yet)
In fact, you were pretty much right on using XMLHttpRequest, it seems to be pretty standard when it comes to dealing with CORS.
I’ve been searching for this error a lot lately :
Reason: CORS header ‘Access-Control-Allow-Origin’ missing
And I don’t think anything can be done with Codepen concerning this, but if you are using C9 or another live server, you could set this header in the backend. Here are the interesting read I’ve had :
I’m reading the links above right now. It seems to be a complex topic.
I was also looking at the book “CORS In Action” (https://www.manning.com/books/cors-in-action), but can’t really afford to buy it right now.
I will get back to this post as and when I learn more and figure out this issue.
In the meantime, I’m going to try it using a jQuery AJAX request. Interesting how it works using jQuery but not JavaScript. The jQuery library must have some special code under the hood to handle CORS maybe ?