如何:将node.js mongodb结果传递给angularjs

How To: Pass node.js mongodb result to angularjs?

本文关键字:angularjs 结果 mongodb node js 如何      更新时间:2023-09-26

所以我有一个使用Node.js查询的MongoDB

使用此功能未发送数据,我不知道出了什么问题

var findIco = function(db, callback) {
   var cursor =db.collection('footIco').find();
   cursor.each(function(err, doc) {
     // console.log(err);
      if (doc != null) {
        console.log(doc); <------ DISPLAY THE DATA IN THE CONSOLE
      } else {
         callback();
      }
   });
}; 
app.get('/icons', function(req, res){
  //calling the function
  MongoClient.connect(url, function(err, db) {
    if(err) {
      console.log(err);
      return res.status(500).send(err);
   }
    findIco(db, function(icons) {
         res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
  console.log(icons);<--------------- IS UNDEFINED
        res.json(icons);
        db.close();
        return;
    });
  });
});
app.listen(8080);

我做错了什么?

您需要使用某种形式的 Web 服务器来创建 API,该 API 将在某个资源收到请求时返回此数据。您可以使用 Angular 应用程序中的$http服务向 API 发出请求。Node Web框架最流行的选择是Express,它包装了Node Core HTTP模块并提供了一个健壮的API。

其他流行的节点.js Web框架

  • 科阿
  • 快乐.js

这些只是几个 Node.js Web 框架,我也排除了任何基于 MVC 的框架,如 Meteor 和 Sails.js因为 Angular 已经提供了这一部分。

要在 Express 中快速启动和运行,您可以使用 express-generator 来搭建基本的 Express API 的基架。然后只需在 Node.js 服务器中为您的函数添加一个路由。

查找科

var findIco = function(db, callback) { 
  db.collection('footIco').find().toArray(function(err, docs) {
    if (err) return callback(err, null);
    return callback(null, docs);
  }); 
} 

节点.js API

app.get('/icons', function getIcons(req, res){
  //calling the function
  MongoClient.connect(url, function(err, db) {
    if(err) {
      console.log(err);
      return res.status(500).json(err);
   }
    findIco(db, function(err, icons) {
      if (err) 
        res.status(500).json(err);
      else {
        if (!icons)
          res.status(204).send();
        else
          res.json(icons);
      }
      db.close();
      return;
    });
  });
});

角度$http呼叫footIconCtrl

app.controller('footIconCtrl', ['$scope', '$http', function($scope, $http){
  $scope.icons = [];
  $http({
    method: 'GET',
    url: 'http://<serverAddress>:<serverPort>/icons'
  })
    .then(function(icons) {
      $scope.icons = icons.data;
    })
    .catch(function(errRes) {
      // Handle errRess
    });
});

在你的角度代码中,你将有一个像getDocument.controller.js这样的文件,其中包含一个函数,其中包含对服务的 http 调用。像这样:

var getDocs = function(){
    var apis = http://localhost:9000/api/getDocs;
    httpRequest.get(apis).
    then(function(docs){
        // Your code to handle the response
    });
};

现在,在服务器端代码中,您可以将响应发送为

CollectionName.find({}, function (err, docs) {
    if (err) return next(err);
    if (!docs) return res.send(401);
    res.json(docs);
});