Single Page Application with Angular.js, Node.js and NeDB (NeDB Module) – updated for Express 4

This post is a proof of concept towards make web application with Javascript based Web Server with light-weight database NeDB.It shows how to create a single page application in Node.js and NeDB (NeDB Module) with Express4.

To make this possible, we have selected –

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 – NeDb

6> Node.js NeDB Module Extention

We have created a Proof of Concept with Javascript based web server, where we have focused on dealing with NeDB with javascript based framework Node.js and angular.js on client side.

Architecture at a glance –

Angular.js Node NeDB

So here are the steps –

Installation –

A> Download and install Node.js from here.

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

Command – npm install nedb (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 –
[javascript]
var application_root = __dirname,
express = require("express"),
path = require("path");

[/javascript]
Here we have initialised the express.js within javascript variables in respect of Node.js concept.
[javascript]
var app = express();
[/javascript]
Here we have initialised the express web server in app variable.
[javascript]
var databaseUrl = "c:/nodeNedb/db/user.db";
var Datastore = require(‘nedb’);
db = {};
db.users = new Datastore({ filename: databaseUrl, autoload: true }); // to autoload datastore

[/javascript]
Here we have made the connection to the nedb database using the Node.js nedb module extension library.
[javascript]
var env = process.env.NODE_ENV || ‘development’;
if (‘development’ == env) {
var bodyParser = require(‘body-parser’);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var methodOverride = require(‘method-override’);
app.use(methodOverride());
app.use(express.static(path.join(application_root, "public")));
var errorhandler = require(‘errorhandler’);
app.use(errorhandler());
}

[/javascript]
Here we have made the configuration related to express.js

Rest Services Code –

[javascript]
app.route(‘/api’).get(function (req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost");
res.send(‘Our Sample API is up…’);
});
[/javascript]
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)
[javascript]
app.route(‘/getangularusers’).get(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.users.find(”, function(err, users) {// Query in NeDB via NeDB 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
}
});
});

[/javascript]
Here we have created another REST api to get all username from user collection and so have done the nedb query.

Our sample api will be  – http://127.0.0.1:1212/getangularusers (Get Method)
[javascript]
app.route(‘/insertangularneuser’).post(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.users.save({email: jsonData.email, password: jsonData.password, username: jsonData.username},
function(err, saved) { // Query in NeDB via NeDB Module
if( err || !saved ) res.end( "User not saved");
else res.end( "User saved");
});
});
[/javascript]
Here we have made a POST request to create an user via REST calling.

Our sample api will be  – http://127.0.0.1:1212/insertangularneuser(Post Method)
[javascript]
//Launch server
app.listen(1212);
[/javascript]
We have made the server to listen at 1212 port.

Now run node appnedbangular.js from command shell.

Angular.js part –

Below is the code in Angular Controller –
[javascript]
‘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/insertangularneuser’; // 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();
}

[/javascript]

Angular Template and HTML

We have referred the Angular Controller in above code
[javascript]
Search: <input ng-model="user">
<div class="span10">
<!–Body content–&gt;
<ul class="users">
<li ng-repeat="user in users | filter:user ">
{{user.name}}
</li>
</ul>
</div>
[/javascript]
We have used the ng-repeat tag to take the users data model from REST communication and shown in HTML
[javascript]
<form name="myform" id="myform1" ng-submit="save()">
<fieldset>
<legend>New User&lt;/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>
[/javascript]

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

To Note : As NeDB is a light-weight Database, which can be embedded in Node WebKit Applications, for fairly large scale database requirement, reader should consider MongoDB in production environment.

Reader can download the complete source-code in GitHub.

Reference :-

https://github.com/louischatriot/nedb

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

Enter your email address:

Delivered by FeedBurner

Leave a Reply

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