【问题标题】:How get data with angular from the backend and send it with node.js for the frontend?如何从后端获取带有角度的数据并使用 node.js 将其发送到前端?
【发布时间】:2015-06-25 08:39:22
【问题描述】:

我正在更改我的 node.js 应用程序,我使用的是 EJS 模板引擎,现在我想使用 angular。

为此,我已经安装了 angular 并且运行良好,但现在我想获取我的数据,为此我正在使用 $http 服务:

(function($) {
  app.controller('EventCtrl', ['$scope', '$http', function($scope, $http){
    $scope.data;

    $http.get('/data').
      success(function(data, status, headers, config) {
        $scope.data = data;

      }).
      error(function(data, status, headers, config) {
        $scope.data = data;

      });

  }]);

}(jQuery));

我正在后端发送数据:

  restAPI.GET(options).then(function (result) {
    res.render('data/index.html', {
      event: result,
    });
  }).then(undefined, function (error) {
    console.log(error);
  });

但它从我使用控制器的同一页面返回 HTML。我在这里做错了什么??

返回的是什么:

<!DOCTYPE html> <html ng-app="app"> <head> <title> Testando Angular </title> </head> <body> <div ng-controller="EventCtrl"> {{data}} </div> </body> <script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="/lib/angular/angular.min.js"></script> <script type="text/javascript" src="/app.js"></script> <script type="text/javascript" src="/controllers/EventCtrl.js"></script> </html>

【问题讨论】:

  • 您告诉节点发送文件。您不想发送数据吗?
  • 但我怎样才能加载 HTML 并仍然发送数据??
  • 您必须具体描述您要完成的任务。
  • 节点应该提供 html 文件 Angular 运行。然后你必须创建一个 API 来发送它需要的任何数据。

标签: javascript angularjs node.js


【解决方案1】:

您需要让节点提供 Angular 所在的页面。 (这只是一个使用 express 的例子) 像这样的:

app.get('/', function(req, res) {
    res.sendFile('../public/index.html');
    res.end();
});

然后你需要设置 Angular 的路由来查询,以便它可以获取数据:

app.get('/api/data', function (req, res) {
        //Get some data here however you do that
    res.json(data) //Send your data back to angular in the callback of your database query ( or whatever you are doing )
    }

您使用res.render() 发送页面。您不想发送页面。如果您使用上面显示的 $http.get 请求,您只想发送数据。获取您的数据并发送至res.json(data)

如果您需要深入了解所有部分如何组合在一起,我建议您完成以下教程: Setting Up a MEAN Stack SPA

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 2019-10-01
    • 1970-01-01
    • 2020-07-02
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    相关资源
    最近更新 更多