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

So, I have MongoDB, which I request using Node.js.

Data is not sent using this function, and I do not know what is wrong.

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

What am I doing wrong?

+4
source share
2 answers

API, , , -. API $http Angular. - Node - Express, Node Core HTTP- API.

Node.js -

Node.js Web Frameworks, , MVC, Meteor Sails.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;
    });
  });
});

Angular $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
    });
});
+2

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

Source: https://habr.com/ru/post/1629595/


All Articles