Javascript Angular.js中的跨原点请求

Javascript Angular.js中的跨原点请求,javascript,json,angularjs,Javascript,Json,Angularjs,我有一个angular.js应用程序,它只能在客户端运行,需要从不同的json文件中获取一些数据 我已经尝试了不同的解决方案来启用CORS,但没有成功 app.js var myApp = angular.module('MyApp', [ 'ngRoute', 'myControllers' ]); myApp.config(function($httpProvider) { //Enable cross domain calls $httpProvider.

我有一个angular.js应用程序,它只能在客户端运行,需要从不同的json文件中获取一些数据

我已经尝试了不同的解决方案来启用CORS,但没有成功

app.js

var myApp = angular.module('MyApp', [
    'ngRoute',
    'myControllers'
]);

myApp.config(function($httpProvider) {
    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;

    //Remove the header used to identify ajax call  that would prevent CORS from working
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
/* Controllers */
var myControllers = angular.module('myControllers', []);

myControllers.controller('NavigationController', ['$scope', '$http',
  function ($scope, $http) {
    $http.get('json/data.json').success(function(data) {
      $scope.data = data;
    });
  }]);
...
controllers.js

var myApp = angular.module('MyApp', [
    'ngRoute',
    'myControllers'
]);

myApp.config(function($httpProvider) {
    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;

    //Remove the header used to identify ajax call  that would prevent CORS from working
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
/* Controllers */
var myControllers = angular.module('myControllers', []);

myControllers.controller('NavigationController', ['$scope', '$http',
  function ($scope, $http) {
    $http.get('json/data.json').success(function(data) {
      $scope.data = data;
    });
  }]);
...
控制台中出现错误

无法加载XMLHttpRequestfile:///.../json/data.json. 仅HTTP支持跨源请求


非常感谢您的帮助,我必须让这个应用程序在chrome和IE上运行,而不是在本地服务器上运行。

我必须这样做。最后,我只需将数据作为对象直接放入脚本文件中,然后将其与其他脚本一起加载。这样应用程序就不需要发出AJAX请求,所以CORS就不会出现在应用程序中


这并不理想,但确实奏效了……

“问题是,出于安全原因,大多数浏览器(不包括firefox)都不支持跨源请求。”?所有现代浏览器和IE8+都支持CORS请求。在这种情况下,最好使用JSONP,因为文件系统不会返回CORS头。或者在应用程序中包含一个最小的Web服务器。@kevinB我更新了这个问题。然而,jsonp解决方案不起作用,我仍然无法使用WebServer。我可以毫无疑问地告诉您,cors解决方案将不起作用。您唯一的选择是根本不使用ajax,可以使用jsonp或脚本include。这很有效!我还包括index.html中的所有模板,如下所述