Single Page Application with Angular.js, Node.js and CouchDB (Cradle Module)

This article has been updated with Express 4. Click here to see the updated article.

Previously we have posted the article for Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module).

Current post is a proof of concept towards make a web application with Javascript based Web Server with CouchDB with Angular.js and Node.js.

The updated post for Express 4 can be found here.

This time we have tried with CouchDB, by definition which is go to link  from go here Apache CouchDB site go to site – 

Apache CouchDB™ is a database that uses JSON for documents, JavaScript for MapReduce queries, and regular HTTP for an API

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

6> Node.js Cradle Module Extention (to make communication with CouchDB)

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

Our initial code can be downloaded here.

Architecture at a glance –

Angular.js Node CouchDB

So here are the steps –

Installation –

A> Download and install source link Node.js from here.

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

Command – npm install cradle (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 initialised the express.js within javascript variables in respect of Node.js concept.

var app = express();

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

var databaseUrl = "sampledb";
var cradle = require('cradle');
var connection = new(cradle.Connection)('http://couchadmin:couchadmin@localhost', 5984, {
auth: { username: 'couchadmin', password: 'couchadmin' }
var db = connection.database(databaseUrl);

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

// Config

app.configure(function () {
  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.header("Access-Control-Allow-Origin", "http://localhost");
  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  – (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
        res.writeHead(200, {'Content-Type': 'application/json'});
        db.view('characters/all', function (err, response) { help with essay //Query in CouchDB View
             response.forEach(function (row) {
             str = str + '{ "name" : "' + row.username + '"},' +'\n';
        str = str.trim();
        str = str.substring(0,str.length-1);
        str = str + ']';
        res.end( str);

Here we have created another REST api to get all username from user collection and so 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. chemistry textbook help Also a note, to run this view creation, we should put -

printable homework calendar [httpd] authentication_handlers = {couch_httpd_auth, null_authentication_handler}

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

This particular feature has taken some time to be discovered by us.

app.get('/createview', function (req, res) { // Before running the Angular Application, the view must be created'_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

Our sample api will be  – (Get Method)'/insertangularcouchuser', 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
  var jsonData = JSON.parse(req.body.mydata);
  var doc = {email:, password: jsonData.password, username: jsonData.username};'\''+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';

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

Our sample api will be  – Method)

// Launch server

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.

References :




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/insertangularcouchuser';// URL where the Node.js server is running
  $scope.codeStatus = "";
  $ = function() {
    // Preparing the Json Data from the Angular Model to send in the Server. 
    var formData = {
      'username' : this.username,
      'password' : this.password,
	  'email' :

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

	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 =;

        error(function(response) {
		console.log("error"); // Getting Error Response in Callback
                $scope.codeStatus = response || "Request failed";
	$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 


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 ">

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()">
        <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><center><button type="submit" >Save now...</button></center></div>

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 updated post for Express 4 can be found 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.

Enter your email address:Delivered by FeedBurner

8 thoughts on “Single Page Application with Angular.js, Node.js and CouchDB (Cradle Module)

  1. Thank you for sharing this with us. I was looking a long time for a tutorial like this. Unfortunately, there are a lot of AngularJS and MongoDB Tuts out there but few AngularJS and CouchDB ones.

      1. Nice. That was the first thing I had to fix ^^ as you know Express 4 does not provide the configure() Method anymore.

        One more thing, this particular post have a lot of copy’n’paste errors. I read a few times “mongodb” and “mongojs”. So if you update the post maybe you want to fix that, too. (The mistakes are mainly in the text not in the listings.)

Leave a Reply

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