错误消息'XMLHttpRequest无法加载.仅AngularJS中的HTTP支持跨源请求

Avr*_*dis 18 javascript angularjs

这是我的代码:

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");
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

我在本地位置有一个简单的JSON文件,我试图使用AngularJShttp方法读取它.我收到以下错误:

XMLHttpRequest无法加载file:/// C:/Users/Avraam/Documents/GitHub/AngularJS/app/js/Services/products.json仅支持HTTP的交叉原始请求.angular.min.js:73错误:发生网络错误.

我的错是什么?我没有使用任何服务器; 我只是用Chrome打开我的索引文件.这是错误吗?如果我想使用该http方法,我应该使用服务器吗?

Dan*_*Dan 22

如果这是用于本地开发并且您使用的是Chrome,则需要使用几个参数运行Chrome以放宽安全性,如下所示:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security
Run Code Online (Sandbox Code Playgroud)

  • 使用本地开发服务器提供页面,此限制不适用.使用XAMPP或者如果你有python,只需运行`python -m SimpleHTTPServer`,你就应该运行一个服务器. (2认同)

Bor*_*ris 14

我通过在服务器上运行我的页面来解决这个问题,就像这样

cd /path/to/dir/with/the/index/file
python3 -m http.server
Run Code Online (Sandbox Code Playgroud)

然后在浏览器中打开http:// localhost:8000.

有关为当前目录提供服务的其他方法,请参阅此问题.


Kyr*_*kos 5

对于Mac用户,相应的命令将是:

open /Applications/Google\ Chrome.app --args --allow-file-access-from-files --disable-web-security
Run Code Online (Sandbox Code Playgroud)