【问题标题】:Angular page not showing JSON data from Node backendAngular 页面未显示来自 Node 后端的 JSON 数据
【发布时间】:2017-11-03 08:21:40
【问题描述】:

我对现代 Web 开发完全陌生,并且一直在通过在线教程学习 MEAN 堆栈。我只是在编写一个允许 CRUD 操作的简单待办事项应用程序。这是使用 MEAN 堆栈(通过 Mongolab 的 Mongo 数据库)和 npmbower 作为包管理器 - 没有脚手架工具或克隆现有应用程序。这是我第一次使用 Node 和 Angular。

我在使用 Angular 显示我的 HTML 页面时遇到了问题。以下是相关文件:

app.js 用于后端(仅包括相关部分):

var express = require('express');
var path = require('path');
var app = express();
var morgan = require('morgan');
var db = require('./db');
var bodyParser = require('body-parser');

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended' : 'true'}));

require('./backend/todo_rest')(app);

module.exports = app;

todo_rest.js:

var TodoSchema = require('./todo_schema');
var path = require('path');

module.exports = function(_app) {
    _app.get('/api/todos', function(req, res) {
         TodoSchema.find({}, function(err, todos) {
            console.log('API GET; data: ' + todos);
            if(err)
                return res.status(500).send("The todos could not be retrieved from the database!");
            return res.json(todos);
        });
    });

    _app.get('*', function(req, res){
         res.sendFile(path.resolve(__dirname + '/../client/views/index.html'));
     });
};

app.js 前端:

var app = angular.module('todosApp', []);

app.controller('todosController', function($scope, $http) {
    $scope.todos = {};

    $http({
        method: 'GET',
        url: '/api/todos'
    }).then(function (success) {
        console.log(success.data);
    }, function (error) {
        console.log('Angular GET error: ' + error.data);
    });
});

index.html:

<!DOCTYPE html>
<html ng-app="todosApp">
<head>
    <meta charset="UTF-8">
    <title>Todos App</title>
    <script src="../../bower_components/jquery/dist/jquery.min.js"></script>
    <script src="../../bower_components/angular/angular.min.js"></script>
    <script src="../app.js"></script>     // <-- this is the frontend's app.js
</head>
<body ng-controller="todosController">
<div>
    <span>Total: {{todos.length}}</span>
    <ul ng-repeat="todo in todos">
        <li>Name: {{todo.title}}, {{todo.completed}}</li>
    </ul>
</div>
</body>
</html>

虽然我确实想支持完整的 CRUD,但现在我只想让 HTML 显示数据库中的所有待办事项。以下是当前的问题:

  • 当我通过localhost:3000 启动页面时,我得到了HTML,但像{{todos.length}} 这样的Angular 元素按原样显示,而不是被评估值替换。基本上,当我启动该页面时,我希望通过调用我在后端公开的/api/todos 端点将所有待办事项显示为列表。我检查了前端app.js 中的console.log 没有被触发。
  • 当我启动localhost:3000/api/todos 时,JSON 结果显示在浏览器中,而不是任何 HTML。我是否需要在 Angular 中使用路由来为同一页面中的每个端点显示不同的视图?

【问题讨论】:

  • 您的控制台是否收到angualr is undefined 错误或类似的错误?
  • @Pengyy 不,不是那样的。我实际上看到消息表明

标签: javascript angularjs json node.js mean-stack


【解决方案1】:

您尚未将 Express 服务器配置为提供静态内容,这就是您的浏览器无法加载 app.js 的原因。因此,Angular 应用程序未初始化。

使用express.static 加载静态内容。

【讨论】:

  • 嗯,根据上面@Pengyy 的评论,似乎是这样。您能否添加一个如何使用 express.static 的示例?我添加了这个 - app.use('/', express.static(path.join(__dirname, '/client/views'))); - 但这无济于事。我必须为其提供 REST 路径吗?
  • 你能分享你的目录结构吗?
  • 我能够让它工作,你提到的 express.static 是必需的。非常感谢!
【解决方案2】:

{{todos.length}} 按原样显示,而不是被评估值替换。

如果你看到这个,这意味着你的 angularjs 应用程序没有成功引导。在您的控制台上查看错误以了解进一步的修复操作。

app.use(express.static(__dirname)); 添加到您的 app.js(nodejs) 以提供静态文件。

我希望通过调用 /api/todos 将所有待办事项显示为列表

您必须将结果从$http.get 设置为$scope.todos

$http({
  method: 'GET',
  url: '/api/todos'
}).then(function (success) {
  console.log(success.data);
  $scope.todos = success.data;      // <-------- set result to $scope.todos
}, function (error) {
  console.log('Angular GET error: ' + error.data);
});

ng-repeat 移动到li

<ul>
    <li ng-repeat="todo in todos">Name: {{todo.title}}, {{todo.completed}}</li>
</ul>

当我启动 localhost:3000/api/todos 时,JSON 结果显示在浏览器中,而不是任何 HTML。我是否需要在 Angular 中使用路由来为同一页面中的每个端点显示不同的视图?

您的意思是直接在浏览器中访问localhost:3000/api/todos?您不必这样做,$http.get 将完成工作并检索结果。目前您不需要routing,因为您只有一个简单的页面。

【讨论】:

  • 我试过了,结果还是一样。在控制台上,我看到 index.html 的
  • @Cygnus 你检查过@Mukesh Sharma 的答案吗?也许您的 app.js 根本没有加载到浏览器中。可以在$scope.todos={}前加console.log()确认。
  • @Cygnus 还要确保404 标记处没有404 错误。
  • 是的,console.log 也没有被执行。我在 Mukesh 的回答中添加了评论。
  • 不走运:(我尝试了 express.static(__dirname + '/client') 以及 express.static('client') 以及 __dirname 作为参数。它必须是app.js 或 index.html 的路径?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
  • 2019-10-26
相关资源
最近更新 更多