Ken
Ken

Reputation: 793

CORS header 'Access-Control-Allow-Origin' missing with AngularJS Web App

I'm developing an AngularJS web app and I'm testing by running the app locally, e.g. it's not on a server. I keep running into the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (Reason: CORS header 'Access-Control-Allow-Origin' missing).1 (unknown)

My SO research tells me this is an error on the server side, but I have been successful getting data back from my iOS app running in the simulator and have used Postman with success.

Per suggestion, I'm running the app through http-server. Same issue.

I added a simple test case with the same results:

$http.get("http://www.yahoo.com")
.then(function (response) {
    alert("Search Results: " + response);
}, function(error) {
    alert("Could not get to Yahoo");
});

This is totally baffling.

Upvotes: 1

Views: 1442

Answers (1)

Daniel Cottone
Daniel Cottone

Reputation: 4480

Based on this comment:

I'm developing an AngularJS web app and I'm testing by running the app locally, e.g. it's not on a server

Then the reason this is not working is obvious: You cannot make asynchronous calls to servers in Javascript with most modern browsers by default if you are not running the javascript from a webserver (http:// instead of file:///). This is a security measure that is built into virtually all browsers. You could possibly get around this by launching the browser with certain flags; for example with Chrome you could run from the command line chrome --allow-file-access-from-files file:///[PATH_TO_FILE]

However it's recommended that you just run the javascript from a web server. This is extremely simple to do, you could use the node package http-server or Python's SimpleHTTPServer to serve the files up right from the directory they are in.

Upvotes: 1

Related Questions