【问题标题】:Angularjs Error in loading external jsonfile from serverAngularjs从服务器加载外部json文件时出错
【发布时间】:2014-09-03 04:51:56
【问题描述】:

我正在尝试从服务器加载 json 文件。这是我的 services.js 文件

angular.module('starter.services', [])

/**
 * A simple example service that returns some data.
 */
.factory('Friends', function($http) {

  var friends;
 //here is the code for server access
  $http.get('http://wwww.root5solutions.com/ionictest/get.json').then(function(msg){
      console.log("console output"+msg.data);
      friends=msg.data;
      console.log("from server"+friends.data);
  });

  return {
    all: function() {
      return friends;
    },
    get: function(friendId) {

      return friends[friendId];
    }
  }
});

但它不能正常工作。这是我的控制台消息

XMLHttpRequest cannot load http://www.root5solutions.com/ionictest/get.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. 

【问题讨论】:

  • 服务器不支持CORS,开启方法见enable-cors.org/server.html
  • 你能给我展示示例代码吗
  • 我刚刚将以下代码添加到我的 js 文件中,但没有工作$http.defaults.headers.put = { 'Access-Control-Allow-Origin': '*' };
  • 由服务器决定是否要提供 CORS 支持。您无法在 javascript 中执行任何操作来启用它。
  • 我在 localhost 中尝试过,但没有成功。是否有可能在 localhost 中

标签: javascript json angularjs ionic-framework


【解决方案1】:

我也遇到了同样的问题。我相信它会解决你的问题,

对于 Windows... 在桌面上创建 Chrome 快捷方式 > 右键单击​​ > 属性 > 快捷方式 > 编辑“目标”路径:>“C:\Program Files\Google\Chrome\Application\chrome.exe” -- args --disable-web-security

注意: 设置此退出chrome后再打开


【讨论】:

【解决方案2】:

您必须将该网址列入白名单

试试这个

.config(function($sceDelegateProvider) {

    $sceDelegateProvider.resourceUrlWhitelist([
        // Allow same origin resource loads.
        'self',
        // Allow loading from our other assets domain.  Note there is a difference between * and **.
        'http://wwww.root5solutions.com/ionictest/**',
    ]);
})

【讨论】:

    【解决方案3】:

    所有这些问题都是因为我只使用浏览器进行了测试。在设备/模拟器上测试时它工作完美。不需要额外的编码来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多