About Piyas De

Piyas is Sun Microsystems certified Enterprise Architect with 10+ years of professional IT experience in various areas such as Architecture Definition, Define Enterprise Application, Client-server/e-business solutions.

Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module)

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

To make this possible, we have selected the following technologies

  1. Angular.js for client side development – Single Page Application
  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)

We have created a Proof of Concept with a Javascript based web server, where we have focused on dealing with NoSql (MongoDB) with the javascript based frameworks Node.js and angular.js on client side. Our initial code can be downloaded here(https://github.com/piyasde/NodeMongoDBAngular).

Architecture at a glance

Angularjs-Nodejs-Angular

So here are the steps:

Installation

A: Download and install Node.js from here(http://nodejs.org/download/).

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

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

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

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

Configuration Code:

Now, we will try to describe the code portion:

var application_root = __dirname,
    express = require("express"),
    path = require("path");

Here we have initialized the express.js within javascript variables in respect of Node.js concept.

var app = express();

Here we have initialized the express web server in app variable.

var databaseUrl = "sampledb"; 
var collections = ["things"]
var db = require("mongojs").connect(databaseUrl, collections);

Here we have made the connection to the mongodb database using the Node.js mongojs module extension library.

// Config

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

Here we have made the configuration related to express.js

Rest Services Code

app.get('/api', function (req, res) {
  res.send('Our Sample API is up...');
});

Here we have made our first REST based web service and tested whether the express.js is up.

Our sample API will be – http://127.0.0.1:1212/api (Get Method)

app.get('/getangularusers', function (req, res) {
	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
	db.things.find('', function(err, users) { // Query in MongoDB via Mongo JS Module
	if( err || !users) console.log("No users found");
	  else 
	{
		res.writeHead(200, {'Content-Type': 'application/json'}); // Sending data via json
		str='[';
		users.forEach( function(user) {
			str = str + '{ "name" : "' + user.username + '"},' +'\n';
		});
		str = str.trim();
		str = str.substring(0,str.length-1);
		str = str + ']';
		res.end( str);
                // Prepared the jSon Array here
	}
  });
});

Here we have created another REST API call to get all usernames from user collection and we have provided the mongojs query.

Our sample API will be – http://127.0.0.1:1212/getangularusers (Get Method)

app.post('/insertangularmongouser', function (req, res){
  console.log("POST: ");
  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 jsonData = JSON.parse(req.body.mydata);

  db.things.save({email: jsonData.email, password: jsonData.password, username: jsonData.username},
       function(err, saved) { // Query in MongoDB via Mongo JS Module
           if( err || !saved ) res.end( "User not saved"); 
           else res.end( "User saved");
       });
});

Here we have made a POST request to create a user via REST calling.

Our sample API will be – http://127.0.0.1:1212/insertangularmongouser(Post Method)

// Launch server
app.listen(1212);

We have made the server listen at port 1212. Now run node appmongodbangular.js from command shell.

Angular.js part

Below is the code in Angular Controller:

'use strict';

var myApp = angular.module('myApp', []); // Taking Angular Application in Javascript Variable

// Below is the code to allow cross domain request from web server through angular.js
myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

/* Controllers */

function UserListCtrl($scope, $http, $templateCache) {

  var method = 'POST';
  var inserturl = 'http://localhost:1212/insertangularmongouser';// URL where the Node.js server is running
  $scope.codeStatus = "";
  $scope.save = function() {
    // Preparing the Json Data from the Angular Model to send in the Server. 
    var formData = {
      'username' : this.username,
      'password' : this.password,
	  'email' : this.email
    };

	this.username = '';
	this.password = '';
	this.email = '';

	var jdata = 'mydata='+JSON.stringify(formData); // The data is to be string.

	$http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server.
            method: method,
            url: inserturl,
            data:  jdata ,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            cache: $templateCache
        }).
        success(function(response) {
		console.log("success"); // Getting Success Response in Callback
                $scope.codeStatus = response.data;
		console.log($scope.codeStatus);

        }).
        error(function(response) {
		console.log("error"); // Getting Error Response in Callback
                $scope.codeStatus = response || "Request failed";
		console.log($scope.codeStatus);
        });
	$scope.list();// Calling the list function in Angular Controller to show all current data in HTML
        return false;
  };	

  $scope.list = function() {
	  var url = 'http://localhost:1212/getangularusers';// URL where the Node.js server is running	
	  $http.get(url).success(function(data) {
		$scope.users = data;
	  });
          // Accessing the Angular $http Service to get data via REST Communication from Node Server 
  };

  $scope.list();
}

Angular Template and HTML

<html lang="en" ng-app="myApp">
.....

We have referred the Angular Application in above code

<body ng-controller="UserListCtrl">
.....

We have referred the Angular Controller in above code

Search: <input ng-model="user">
<div class="span10">
    <!--Body content-->
    <ul class="users">
        <li ng-repeat="user in users | filter:user ">
            {{user.name}}
        </li>
    </ul>
</div>

We have used the ng-repeat tag to take the users data model from REST communication and shown in HTML

<form name="myform" id="myform1" ng-submit="save()">
    <fieldset>
        <legend>New User</legend>
            <div class="control-group">
                <center><input type="text" placeholder="User…" ng-model="username" size=50 required/></center>
                <center><input type="text" placeholder="Password…" ng-model="password" size=50 required/></center>
                <center><input type="text" placeholder="Email…" ng-model="email" size=50 required/></center>
            </div>
    </fieldset>
    <p>
         <div><center><button type="submit" >Save now...</button></center></div>
    </p>
</form>

We have used the ng-submit tag to send the user data model from REST communication and sent to node server to save in MongoDB.

  • Reader can download the complete source-code in GitHub (https://github.com/piyasde/NodeMongoDBAngular).

handson-web-appThis is article is an excerpt from the book “Hands-On Web Application with Javascript Frameworks and NoSQL“.

The technology is transforming traditional structural data programming to non-structural one, server side work are emerging with JavaScript.

So this book is a quick walk-through of some of those tools and how those are integrated… with codes hands-on.

We may think this e-book as a collective starting point of some of new technologies in Web Frameworks for coming days of newcomers…

Get the book here!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

3 Responses to "Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module)"

  1. thank you for sharing. Really cool document!

  2. Sharan says:

    Hello I have followed your tutorial. I have a question regarding the database. My database is on the server to which I want ti link my angular and HTML. Is it possible to do so with nodejs(API) and angular?

  3. PapuPager says:

    Thank you for the post its really helpful..

Leave a Reply


eight − = 6



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close