Single Page Application with Angular.js, Node.js and CouchDB (Cradle Module) – (Updated for Express 4)

We posted the article on Single Page Application with Angular.js, Node.js and CouchDB (Cradle Module) with Express 3. Current post is a way to migrate the same with Express 4.
This article describes a way to make a web application with Javascript based Web Server with CouchDB with Angular.js and Node.js.

Here we have selected

  • Angular.js for client side development – Single Page Application
  • Cross Domain Communication in between Angular.js and Node.js
  • Node.js for server side development
  • Rest based web service creation with express.js (Express 4)
  • Database – CouchDb
  • Node.js Cradle Module Extention (to make communication with CouchDB)
  • Making CouchDB views with Map-Reduce to fetch the data

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

Architecture at a glance –

Angular.js Node CouchDB

Steps

Installation

  • Download and install Node.js from here.
  • To Develop the application we need to install cradle module for Node.js
    Command – npm install cradle (should be connected to internet)
  • We need to install express.js for node.jsCommand – 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 = "sampledb";
var cradle = require(‘cradle’);
var connection = new(cradle.Connection)(‘http://admin:admin@localhost’, 5984, {
auth: { username: ‘admin’, password: ‘admin’ }
});
var db = connection.database(databaseUrl);
[/javascript]

Here we have made the connection to the couchdb database using the Node.js cradle module extension library.

[javascript]
// Config
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 which is very much different from Express 3.

In Express 3 the same portion was written as

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

This makes a little sense how the Express 3 is migrated to Express 4.
In Express 4 app.use(app.router); is removed. Instead it is added with the Rest services.The way of configuration is also changed as well as the changes reflected in use of bodyParser() ,methodOverride() ,methodOverride() ,errorHandler({..}).

Rest Services Code

[javascript]
app.route(‘/api’).get(function (req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost");
res.send(‘Express API is running’);
});
[/javascript]

Here we have made our first REST based web service and tested whether the express.js is running.Our sample api will be http://127.0.0.1:1212/api or http://localhost:1212/api

[javascript]
app.route(‘/getangularusers’).get(function (req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
res.writeHead(200, {‘Content-Type’: ‘application/json’});
str='[‘;
db.view(‘characters/all’, function (err, response) {
response.forEach(function (row) {
//console.log("%s is on the %s side of the force.", row.name, row.force);
str = str + ‘{ "name" : "’ + row.username + ‘"},’ +’\n’;
});
str = str.trim();
str = str.substring(0,str.length-1);
str = str + ‘]’;
res.end( str);
});
});
[/javascript]

Here we have created another REST api to get all username from user collection and so we have done the cradle query.

CouchDB View Creation

This view creation is to be executed, before running the Angular Client Application to get specific set of data from couchdb.
To run this view creation, we should put –

[httpd]
authentication_handlers = {couch_httpd_auth, null_authentication_handler}

in the local.ini file of <>/etc/couchdb folder to execute this map function without being the admin user.

So the REST api of view creation is

[javascript]
app.route(‘/createview’).get(function (req, res) { // Before running the Angular Application, the view must be created
db.save(‘_design/characters’, { // Main View Family Name
all: { // A particular set of data selection by javascript map-reduce
map: function (doc) {
if (doc.username) emit(doc.username, doc); // specific code to execute map function on each document
}
}
});
});
[/javascript]

and the sample api will be – http://127.0.0.1:1212/getangularusers (Get Method).

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

[javascript]
app.route(‘/insertangularcouchuser’).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);
var doc = {email: jsonData.email, password: jsonData.password, username: jsonData.username};
db.save(‘\”+Math.random()+’\”, doc, function (err, res) {
if (err) {
// Handle error
res += ‘ SAVE ERROR: Could not save record!!\n’;
} else {
// Handle success
res += ‘ SUCESSFUL SAVE\n’;
}
});
});
[/javascript]

Our sample api will be – http://127.0.0.1:1212/insertangularcouchuser (Post Method – accessed by client side)

[javascript]
// Launch server
app.listen(1212);
[/javascript]

We have made the server to listen at 1212 port.

Now run node appcouchdbangular.js from command shell. This is our node.js specific code file.

For references :

Angular.js part –

Below is the code in Angular Controller –

[javascript]
‘use strict’;

var myApp = angular.module(‘myApp’, []); // <strong>Taking Angular Application in Javascript Variable</strong>

// <strong>Below is the code to allow cross domain request from web server through angular.js</strong>
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/insertangularcouchuser’;// <strong>URL where the Node.js server is running</strong>
$scope.codeStatus = "";
$scope.save = function() {
//<strong> Preparing the Json Data from the Angular Model to send in the Server.</strong>
var formData = {
‘username’ : this.username,
‘password’ : this.password,
’email’ : this.email
};

this.username = ”;
this.password = ”;
this.email = ”;

var jdata = ‘mydata=’+JSON.stringify(formData); // <strong>The data is to be string.</strong>

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

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

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

$scope.list();
}

[/javascript]

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 CouchDB.

The previous article, on which this article is based, is here.

Reader can download the complete source-code in GitHub.

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

2 thoughts on “Single Page Application with Angular.js, Node.js and CouchDB (Cradle Module) – (Updated for Express 4)

Leave a Reply

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