Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error message 'XMLHttpRequest cannot load. Cross origin requests are only supported for HTTP in AngularJS'

This is my code:

MyAppModule.factory('EventData', function($http,$log){
    return {
        getEvent : function(successcb){

            $http({method: 'GET', url: './js/Services/products.json'}).

            success(function(data) {
                $log.info("success");
            }).
            error(function(data) {
                $log.info("error");
            });
        }
    };
});

I have a simple JSON file in a local location, and I am trying to read it using the http method of AngularJS. I am getting the following error:

XMLHttpRequest cannot load file:///C:/Users/Avraam/Documents/GitHub/AngularJS/app/js/Services/products.json Cross origin requests are only supported for HTTP. angular.min.js:73 Error: A network error occurred.

What is my mistake? I am not using any server; I am just openning my index file with Chrome. Is this the mistake? Should I use a server if I want to use the http method?

like image 201
Avraam Mavridis Avatar asked Mar 12 '14 18:03

Avraam Mavridis


2 Answers

If this is for local development and you are using Chrome, you need to run Chrome with a couple of arguments to relax security like this:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security
like image 89
Dan Avatar answered Sep 28 '22 07:09

Dan


I fixed this problem by running my page off a server, like this

cd /path/to/dir/with/the/index/file
python3 -m http.server

then open http://localhost:8000 in your browser.

For other ways of serving the current directory, see this question.

like image 35
Boris Avatar answered Sep 28 '22 07:09

Boris