Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module) – (Updated for Express 4) – Part 1

We had posted article for Developing Web Application with Node.js, Express.js and MongoDB (MongoJS module) .

Here we have updated the application with Express 4, added testing for both Angular.js and node.js related methods.

We will cover all the testing related works in our other posts, which will come eventually.

So our application is now as discussed below –

This post is a proof of concept towards making web application with Javascript based Web Server. This technological stack is popularly known as MEAN  Stack.

To make this, we had selected –

1> Angular.js for client side development – Single Page Application (SPA)

2> Cross Domain Communication in between Angular.js and Node.js

3> Node.js for server side development

4> Rest based web service creation with express.js

5> Database – MongoDb

6> Node.js MongoDb Module Extention (mongojs)

In this POC we have focused on dealing with NoSql (MongoDB) with javascript based framework Node.js and angular.js on client side.

In current part, we have concentrated on server side code and in part 2 we had concentrated on client side code for this application.

Reader can download the complete source-code in GitHub.

Architecture at a glance –

Angularjs Nodejs MongoDB

Installation –

A> Download and install Node.js from here.

B> To Develop the application we need to install mongojs module for Node.js

Command – npm install mongojs (we should be connected to internet)

C> We need to install express.js for node.js

Command – npm install express  (we should be connected to internet)

Here express 4.0 version will be installed.

Configuration Code –

Now, we will try to describe the code portion –

Express.js setup code in server boot up code (min-server.js)-

 
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.use( bodyParser.urlencoded() );       // to support JSON-encoded bodies
app.use(compression());

Routing in server should be –

 
// routes ======================================================================
require('./server-routes.js')(app); // load our routes and pass in our app

Now the routing to different paths in server is defined in (server-routes.js)

 
var express = require('express'); // Initialized the express variable
var userwork = require('./dataaccess/userdao'); // modularize code for mongodb in userdao class 

Rest Services Code to get the list of user –

 
             app.route('/getusers') // this is the router in express
		// show the form (GET http://localhost:8080/getusers)
		.get(function(req, res) { // get function for the route path
			res.header("Access-Control-Allow-Origin", "http://localhost"); 
			res.header("Access-Control-Allow-Methods", "GET, POST");
                        // The above 2 lines are required for Cross Domain Communication
                        // (Allowing the methods that come as Cross Domain Request 
			//*********************//
			userwork.getUser(function (err, userString) { // Get list of users in string
				console.log(userString);
				var userJson = JSON.parse(userString);

				if (err) {
				  res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error');
				}

				if(userJson.length>0)
				{
					res.writeHead(200, {'Content-Type': 'application/json'});
					res.end(userJson);
				}
				else
				{
					res.end('No user found');
				}
			  });
			});

So our sample api will be  – http://127.0.0.1:1212/api (Get Method)

Rest Services Code to insert user –

 
            app.route('/insertuser')  // this is the router in express
		.post(function(req, res) { // Post function in the router
		        res.header("Access-Control-Allow-Origin", "http://localhost");
			res.header("Access-Control-Allow-Methods", "GET, POST");
                        // The above 2 lines are required for Cross Domain Communication
                        // (Allowing the methods that come as Cross Domain Request 
			console.log(req.body);
			console.log(req.body.mydata);
			var jsonBody = req.body;
			userwork.insertUser(req.body.mydata, function (err, contents) {
			        if (err) {
					res.end( "User not saved");
				}
				else {
					res.end( "User saved");
				}
			});
		});

Our sample api will be  – http://127.0.0.1:1212/insertuser(Post Method)

To launch our server, we have following code in min-server.js

 
var port     = process.env.PORT || 8080;
.....
// Launch server
app.listen(port);

Here we have made the server to listen at 8080 port.

Now we can dig at the code of userdao.js in dataaccess directory –

insert in mongodb through mongojs module –

 

function insertUser(jsonVar, cb) {
  var jsonData = JSON.parse(jsonVar);
  users.save({email: jsonData.email, password: jsonData.password, username: jsonData.username}, function(err, saved) {
  	if( err || !saved ) 
		return cb(err,'Internal Server Error'); // here the callback registration
  	else 
		return cb(null,JSON.stringify(saved)); // here the callback registration
  });
}

get users data from mongodb through mongojs module –

 

function getUser(cb) {
  users.find(function(err, usersrec) {
	if( err || !usersrec) 
	   return cb(err,'Internal Server Error'); // here the callback registration
	else 
	{
		if (usersrec == '')
			return cb(null,JSON.stringify("[]")); // here the callback registration
		str='[';
		usersrec.forEach( function(user) {
			str = str + '{ "name" : "' + user.username + '","email" : "'+ user.email +'"},' +'\n';
		});
		str = str.trim();
		str = str.substring(0,str.length-1);
		str = str + ']';
		return cb(null,JSON.stringify(str)); // here the callback registration
	}
  });
}

Here the methods are exported through userdao class with the following code –

 
module.exports.insertUser = insertUser;
module.exports.getUser = getUser;

After completing the server side development, we will run Now run node min-server.js from command shell to start the server.

Our part 2 code will explain Angular.js client part.

If you find this article helpful, you can connect us in Google+ and Twitter.

9 thoughts on “Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module) – (Updated for Express 4) – Part 1

    1. Hi,

      Please take a look at your mongodb service. Whether it is running or not.

      For http://127.0.0.1:8080/getusers

      It is returning empty array, as there is no user in the mongodb collection.

      And for

      http://127.0.0.1:8080/insertuser

      It is a POST request. So you will not be able to test it in borowser.

      Either you need to set up angular.js app for this – you can follow –

      http://www.phloxblog.in/single-page-application-angular-js-node-js-mongodb-mongojs-module-updated-express-4-part-2/

      or you can use – mocha for testing –

      http://www.phloxblog.in/server-side-testing-mocha-node-js/

      Thanks

  1. Hi, having looked all over the net for a decent tutorial with an example I can use and see for my self how I can get to grips with nosql, angular etc.. I find that each guide makes way too many assumptions.. I get the feeling that if you don’t know about one, you not meant to know by default know about the other.

    So my question is, how the hell do you actually install this example, where do the files actually go? (Windows, OSX or even Linux?! I have Windows and OSX though i prefer Windows)

    I have the windows, nodejs, mongodb module and even git installed but your guide says nothing on where the files from Github actually go.

    I am seeing this more and more where assumptions are made that people like my self coming from different programming backgrounds are just simply meant to know what do to and its very frustrating…

    Can you please be nice and help me out with this so i can get on with my learning, rather than having to always hit stumbling blocks.

    Thanks.

    1. Hi Karis,

      Thanks for writing,

      First of all, if all of the above pre-requisites are installed,
      If you download the source code from Github, then try to install all the required dependencies by typing ‘ npm install’ in the root directory of the application.

      All the required modules will be installed in node_modules directory, if installed locally.

      Also, can you you please send me specific questions by points? So that I can answer those specific questions.

      Hope that will help you.

      Thanks

  2. Where did u hosted all these stuff ??

    url such as “http://localhost:8080/insertuser” wont work right ??

    How to achieve this then ??

    1. Hi Rahul,

      Thanks for contacting. You can have all the required software installation instruction in the post. Also there is a link to github repository for the full source code. Here I am giving it again – https://github.com/piyasde/express4mongoangular. Please go through the instructions and get acquainted with the source code for the MEAN Stack Eco Cycle.

      For any specific issue, you can contact here.

      Hope this will help you.

      Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *