0

I have a node.js server which is running locally on my computer. And I am developing html page with js-code:

var MainController = function($scope, $http) {

    var onCountComplete = function(response) {
        $scope.count = response.data;
    };

    var onError = function(reason) {
        $scope.error = "Could not fetch data";
    };

    $http.get("http://localhost:1337/api/count")
        .then(onCountComplete, onError);

    $scope.message = "hello";
};

I get the error when I were running this code:

XMLHttpRequest cannot load http://localhost:1337/api/count. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.

I have tried to launch the Chrome with --allow-file-access-from-files key, but it doesn't helps. Is there a way to avoid this error during development?

ceth
  • 44,198
  • 62
  • 180
  • 289
  • Is on your api server CORS enabled? – Alborz Oct 06 '14 at 18:51
  • Can you try to set `Access-Control-Allow-Origin: *` response header on the server-side? – Oleg Oct 06 '14 at 18:52
  • You doing cross-domain request and this is the problem. You have to either place server and client on the same domain or enable CORS on server – hindmost Oct 06 '14 at 18:52
  • How can I do it (enable CORS on the server) in node.js case? – ceth Oct 06 '14 at 18:53
  • If you're using Express, [this link](http://enable-cors.org/server_expressjs.html) may help. – Oleg Oct 06 '14 at 18:56
  • You can serve the Angular code from `http://localhost:1337` and this should work okay – Explosion Pills Oct 06 '14 at 19:00
  • @demas What the scheme of web page the runs the script? If it's `file://`, that's your problem. If so, this is a duplicate of [Origin null is not allowed by Access-Control-Allow-Origin](http://stackoverflow.com/questions/8456538/origin-null-is-not-allowed-by-access-control-allow-origin) – apsillers Oct 06 '14 at 19:53

1 Answers1

0

If you're using Apache, you can try this solution. This has worked for me on a few small projects. Just add these lines to your .htaccess file. Customize as needed though, my example below is rather permissive and you may only need POST or a specific origin for example.

Header set Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET, POST, OPTIONS, DELETE"
Header add Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type"
Kelly Kiernan
  • 355
  • 3
  • 11