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

So I have a MongoDB that I query using Node.js.
The data is not being sent out using this function and I dont 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?

You would need to use some form of Web Server to create an API that will return this data when a request is received at a certain resource. You can make the requests to your API using the $http service in your Angular app. The most popular choice for a Node web framework is Express, this wraps the Node Core HTTP Module and gives a robust API.
Other Popular Node.js Web Frameworks
Koa
Hapi.js
These are just a couple of Node.js Web Frameworks, I also excluded any frameworks that are MVC based frameworks such as Meteor and Sails.js since Angular already is providing that piece.
To get up and running quickly in Express, you can use express-generator to scaffold out a basic Express API. Then just add a route for your function in your Node.js server.
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 call in 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
});
});

In your angular code, you will have a file like getDocument.controller.js with a function with an http call to your service. Something like this :
var getDocs = function(){
var apis = http://localhost:9000/api/getDocs;
httpRequest.get(apis).
then(function(docs){
// Your code to handle the response
});
};
Now in your server side code, you can send the response as
CollectionName.find({}, function (err, docs) {
if (err) return next(err);
if (!docs) return res.send(401);
res.json(docs);
});

Related

How to use AngularJS $http to fetch data returned by an ExpressJS endpoint?

I have an ExpressJS route as below:
var exec = require('child_process').exec;
app.get('/someURL', function (req, res) {
exec('cp file1 file2', (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
// the *entire* stdout and stderr (buffered)
console.log('stdout: ' + stdout);
console.log(stderr);
});
return stdout;
})
This is basically to run a CLI command when the user goes to the specified route on the web app.
In my AngularJS controller I have the following function:
function getData() {
let deferred = this.$q.defer();
this.$http({
method: 'GET',
url: '/someURL'
}).then((response) => {
deferred.resolve(response);
}, (error) => {
deferred.reject(error);
});
return deferred.promise;
}
this.getData().then(function(response) {
console.log(response);
}).catch(function(err) {
console.log(err, err.stack);
});
When I run the application, I am getting the html code as the response at console.log(response), instead of stdout. How do I correct that?
app.get('/someURL', function (req, res) {
// Here do the processing that you need to do
res.send('response');
})
In your expressJS server, you are intercepting the request but you are not sending anything back. You have to specifically send something back using the 'res' object from the funtion parameter. You can add http status codes too like
res.status('200').send(data);

Node.js send JSON to client

I am new to Node.js and javascript. I have a problem which I can't solve. I have a Node application, also I am using Express.
My problem: I have a script that sends a JSON to my server. This data is then stored in my MongoDB. What i want to do now is display that data on another page. This is what i have:
router.post('/', function(req, res, next) {
MongoClient.connect(url, function(err, db) {
var dbase = db.db("db");
dbase.collection('db').insertOne(req.body, function (err, result) {
if (err)
console.log('error');
else
console.log('success');
res.render('result');
});
});
});
What would be the best way to display the data stored in req.body? And could I send it to 'result'? Or should I display the data within the InsertOne-Function?
Please read the express documentation for all the details.
The JSON response can be sent using res.json() method.
Your code will look like this -
router.post('/', function(req, res, next) {
MongoClient.connect(url, function(err, db) {
var dbase = db.db("db");
dbase.collection('db').insertOne(req.body, function (err, result) {
if (err)
console.log('error');
else
res.json(result);
});
});
});

Can i use returning promise in socket.io "socket.on(eventName, callback)"?

Can i use returning promise in socket.io "socket.on"? Like the following code.
socket.on('news', function (data) {
return News.findOne({id: data.id})
.then((news) => {
socket.emit('event', data.body);
return news;
})
});
In your socket.io server side part of your code you could use the node module 'node-mongodb-native' which in its documentation section shows you how to save something to your mongoDB instance like this:
var MongoClient = require('mongodb').MongoClient, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
// Insert a single document
db.collection('inserts').insertOne({a:1}, function(err, r) {
assert.equal(null, err);
assert.equal(1, r.insertedCount);
// Insert multiple documents
db.collection('inserts').insertMany([{a:2}, {a:3}], function(err, r) {
assert.equal(null, err);
assert.equal(2, r.insertedCount);
db.close();
});
});
});

How to disable cache in CRUD application AngularJS + NodeJS

I have problem with cache in Internet Explorer. In Chrome everything works fine. When I try to add item in my application then data doesn't refresh. I have to press Ctrl+R to refresh data.
I'm using:
NodeJS / express (backend)
AngularJS (frontend)
Jade (view engine)
MongoDB / mongoose (database)
Jade view:
form(name="AddPartner")
.col-md-4
|Name:
input.form-control(type='text', name='name' ng-model="dataPartner.name")
Script:
var myApp = angular.module('myApp', []);
myApp.controller("myCtrl", function($scope, $http){
$scope.loadPartnersData = function () {
$http.get("/main/partner-list").then(function(result) {
$scope.partnerList = result.data.partnerList;
});
};
$scope.loadPartnersData();
$scope.addPartner = function(data) {
$http.post(addPartner, data)
.then(function(response) {
console.log(response);
});
$scope.loadPartnersData();
window.alert("Done!");
};
My backend:
router.get('/partner-list', function (req, res) {
Partner.find({}, function (err, partnerList) {
if (err) throw err;
res.json({ partnerList: partnerList });
});
});
router.post('/addPartner', function (req, res) {
new Partner({ name : req.body.name, shared : req.body.shared }).save(function (err) {
if (err) console.log(err);
res.writeHead(200, { 'Content-Type': 'application/json' });
});
});
Write your response like res.json(response); and also move your $scope.loadPartnersData(); call inside the then portion of your promise. ;)

How to register async middleware module within express.js app?

I'm working on an express app that uses the node_acl module with a MongoDB backend. I made a module that creates an instance of node_acl and configures it asynchronously. This middleware should be called as the second middleware on the stack to control request access.
// myModule.js
exports.init = function(callback) {
mongodb.connect("mongodb://localhost:27017/mydb", function(error, db) {
var mongoBackend = new acl.mongodbBackend(db, 'acl_');
acl = new acl(mongoBackend);
// Defining roles for acl
....
acl.addRoleParents('..', '..', function(err){
if (err) callback(err, acl);
acl.addRoleParents('..', '..', function(err){
if (err) callback(err, acl);
acl.addRoleParents('..', ['..','..'], function(err){
if (err) {
callback(err, acl);
} else {
callback(null, acl);
};
});
});
});
});
};
How can I register this module to be the second middleware of the stack? Do I need to edit myModule.js in some way?
Thank you guys
That module already provides an Express middleware, so it's as simple as:
// ...
var myModule = require('./myModule');
myModule.init(function(err, acl) {
if (err) throw err;
// insert first `app.use()` here
app.use(acl.middleware());
// insert other middleware/route handlers here
});
Although I should note a couple of things with your existing code:
if (err) callback(err, acl); should be changed to if (err) return callback(err); to prevent further execution after the callback is called.
if (error) return callback(error); is missing right inside the mongodb.connect() callback in case there is a connection error.

Categories