JSON 文件未被 Angular $HTTP 读取 MEAN.JS 应用程序

JSON file not being read with Angular $HTTP Get in MEAN.JS application

我正在开发一个带有 MEAN.JS (www.meanjs.org) 的 Web 应用程序,我正在尝试使用 AngularJS $HTTP Get 请求和我的 JSON 文件控制器,这样我就可以在我的一个页面中从中提取数据。由于某些奇怪的原因,JSON 文件 (foo.json) 从未被读取过。即使我只是尝试通过 http://localhost:3000/foo.json 访问文件,它也不会显示。它也不会在控制台中显示任何错误。我已将 JSON 文件放置在我的模块、根目录、视图目录等任何地方,随便你怎么命名。只有当我使用像 "modules/core/json/foo.json" 这样的较长路径名时,我才会收到带有 "Failed to load resource: the server responded with a status of 404 (Not Found)" 错误的 Chrome 控制台错误。这是我的控制器代码:

angular.module('core').controller('FooController', ['$scope', '$http',
function ($scope, $http) {
$http.get('foo.json').success(function(data){
  console.log(data);
  $scope.products = data;
});
}
]);

FOO.JSON 文件放在我的核心模块文件夹的根目录中,在视图中,甚至在应用程序的根目录中。

[
  {

        "id" : 3,
        "name": "Orange Theme",
        "description": "Consectetur adipiscing elit. Vestibulum condimentum turpis nec nunc scelerisque convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas id diam enim.",
        "type": "Joomla",
        "price": 12.99,
        "images": [
            {
                "name": "orange.jpg"
            }
        ]
    },
    {
        "id" : 4,
        "name": "Gray Theme",
        "description": "Consectetur adipiscing elit. Vestibulum condimentum turpis nec nunc scelerisque convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas id diam enim.",
        "type": "Joomla",
        "price": 12.99,
        "images": [
            {
                "name": "gray.jpg"
            }
        ]
    },
    {
        "id" : 5,
        "name": "Purple Theme",
        "description": "Consectetur adipiscing elit. Vestibulum condimentum turpis nec nunc scelerisque convallis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas id diam enim.",
        "type": "html5",
        "price": 9.99,
        "images": [
            {
                "name": "purple.jpg"
            }
        ]
    }
]

我一直对这个感到沮丧,因为它看起来很简单!不确定它是否与 JSON 文件没有开箱即用有关,我需要在 Express 等中进行更改。任何帮助将不胜感激。

一个可能的解决方案是将 JSON 数据添加到 mongodb 数据库并从那里检索数据。我已经使用 $hhtp 像这样从控制器请求一些数据。

创建服务以通过 $http:

检索数据
angular
.module('yourModule')
.factory('YourService', function($http) {
  var urlBase = '/api/restfull/url';
  var aService = {};

  aService.getThemes = function() {
    return $http.get(urlBase);
  };
  return aService;
});

在您的控制器中注入 YourService 并执行此操作:

YourService.getThemes().then(function(data) {
  vm.themes = data.data;
});

在您的服务器端添加特定路由 '/api/restfull/url' 像这样

 app.route('/api/restfull/url').all(sitesPolicy.isAllowed)
.get(themes.getThemes);

在您的服务器控制器中处理请求并使用 mongodb JSON 数据进行响应:

exports.getThemes = function(req, res) {
  Themes.find().exec(function(err, themes) { //Themes is your mongodb instance
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(themes);
    }
  });
};

我已将您的示例缩减为

<body ng-app="core">
    <div ng-controller="FooController">
        <div ng-repeat="product in products">
            {{ product }}
        </div>
    </div>

    <script>
        var app = angular.module('core', []);

        app.controller('FooController', function($scope, $http){
            $http.get('foo.json')
                    .success(function(data){
                        console.log(data);      // data appears on console
                        $scope.products = data;
                    })
                    .catch(function(err){
                        console.log(err);       // error if any
                    });
        })
    </script>
</body>

并使用您的 JSON 文件我得到了正确的输出。

根据您上面的评论(抱歉,我还不能发表评论),您的代码的 ng-repeat 部分似乎有问题。如果您正在使用另一个 JSON 文件,您可能会在 ng-repeat 中遇到关键错误,在这种情况下,以下内容可能会有所帮助

<div ng-repeat="product in products track by $index"></div>

根据 Angular docs

由于无法从浏览器访问您的 JSON 文件,听起来您没有从 Node.js 提供静态文件。在您的节点 app.js 文件中,您需要初始化相关中间件以提供静态文件 - 例如,要在您的节点应用程序中提供目录 'public' 中的文件,请添加:

app.use(express.static(path.join(__dirname, 'public')));

如果该文件位于您的 Node 应用程序的根目录中,则默认情况下无法通过 HTTP 访问它。因此,如果您将 JSON 文件放在名为 public 的目录中,并将上述行包含在您的节点 app.js 文件中,那么它应该可以在 http://localhost:3000/foo.json