如何将 Node.js MongoDB 结果传递给 AngularJS?

4

我使用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);

我做错了什么?

2个回答

2
您需要使用某种Web服务器创建一个API,当请求到达特定资源时,该API将返回此数据。您可以在Angular应用程序中使用$http服务向API发出请求。最受欢迎的Node Web框架选择是Express,它包装了Node Core HTTP模块并提供了强大的API
其他流行的Node.js Web框架如下: 这些仅是一些Node.js Web框架,我还排除了任何基于MVC的框架,例如MeteorSails.js,因为Angular已经提供了该部分。
要快速启动Express,可以使用express-generator来搭建基本的Express API。然后只需在Node.js服务器中添加一个路由以执行您的函数即可。 findIco
var findIco = function(db, callback) { 
  db.collection('footIco').find().toArray(function(err, docs) {
    if (err) return callback(err, null);

    return callback(null, docs);
  }); 
} 

Node.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;
    });
  });
});

footIconCtrl 中调用 Angular 的 $http 方法

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
    });
});

我该如何定义$http? - MadeInDreams
1
你不需要定义它,因为它已经在 Angular 核心模块中提供了。你可以通过将它注入到控制器的依赖项中来访问它,例如:app.controller('footIconCtrl', ['$scope', '$http', function($scope, $http) {}); - peteb
2
你的Angular应用程序需要由你的Express应用程序提供服务,或者它们需要在同一个域中,即它们都需要来自localhost - peteb
1
请查看此帖子,其中的问题和答案代码示例应该能够帮助您解决这个问题。 - peteb
显示剩余4条评论

1
在您的Angular代码中,您将拥有一个名为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);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接