Develop Web Application with Node.js, Express.js REST Service and Neo4j (neo4j-js module) – Updated for Express 4


We have posted Develop Web Application with Node.js, Express.js REST Service and Neo4j (neo4j-js module) .This article is a proof of concept towards make a web application with Javascript based Web Server with Node.js and Neo4j and this time the same is updated with Express 4

To make this possible, we have selected –

1> Node.js for server side development

2> Rest based web service creation with express.js (Express 4)

3> Graph Database – Neo4j

4> Node.js Neo4j Module Extention (neo4j-js)

We have created a Proof of Concept with Javascript based web server, where we have focused on dealing with Neo4j(Graph Database) with javascript based framework Node.js.

We have taken help of the Neo4j-js module, which are discussed in Neo4j Site and the Github project contribution from Bret Copeland.

Our initial code can be downloaded here.

We have taken reference Data Model of Neo4j Graph Database for this application from our previous knowledge on Neo4j.

For reference of the Neo4j Graph Database Model , take a look at our previous 2 articles –

1> Case Study in Graph Database in Context of Neo4j Cypher Query

2> Neo4j Cypher Queries for Sample Graph Database

Architecture at a glance –

NodeJS Neo4j Architechture

So here are the steps –

Installation –

A> Download and install Node.js from here.

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

Command – npm install neo4j-js (should be connected to internet)

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

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

D> We need to install http status

Command – npm install http-status (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"),
    HTTPStatus = require('http-status'); // To return http status for error codes

var config = require('./config');

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

We have introduced another js file – config.js to put all the neo4j configuration related information.

 
var app = express();

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

 
var neo4j = require('neo4j-js');

Here we have made the Node.js Neo4j-js module available .

 
var neo4jurl = process.env.NEO4J_URL ;
neo4jurl = neo4jurl +'/db/data/';

Here the Neo4j Database server url is set from configuration file.

 
var query = [ 'START me=node:node_auto_index(name={inputusername}) MATCH me--%gt;friend-->friend_of_friend where 
(friend_of_friend.entitytype={inputentitytype}) RETURN friend_of_friend;'	];
var insertquery = [ 'CREATE (user {entitytype:{inputentitytype}, name : {inputname}}) return user;' ];
var queryforallrelation = [ 'start n = node:node_auto_index(name={inputusername}) match(n)--(x)  return x;'];

Here all the query variables are set with Neo4j Cypher Queries.

 
// Express 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());
}

Here we have made the configuration related to express.js

Rest Services Code –

 
app.route('/api').get(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.route('/friendoffriend/:username').get(function (req, res){
	res.set({'Content-Type': 'text/json'});
	username = req.params.username;
	type = 'user';
	neo4j.connect(neo4jurl, function (err, graph) {

			graph.query(query.join('\n'), {inputusername : username, inputentitytype :type} ,function (err, results) {	
				if (err) {
					res.status(HTTPStatus.INTERNAL_SERVER_ERROR).send('Internal Server Error');
				}
				else {
					res.status(HTTPStatus.OK).send(JSON.stringify(results));
				}
			});	
	});
});

Here we have created REST api to get user information from Neo4j Nodes Collection and so have done through Neo4j-js Extention Library. We have made a query for ‘Friend of Friend’ in Cypher Query Language.

More information about Neo4j Cypher query can be found in Neo4j Cypher Queries for Sample Graph Database.

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

 
app.route('/insertuser/:username').get(function (req, res){
	res.set({'Content-Type': 'text/json'});
	username = req.params.username;
	type = 'user';
	neo4j.connect(neo4jurl, function (err, graph) {
			graph.query(insertquery.join('\n'), {inputname : username, inputentitytype :type} ,function (err, results) {	
				if (err) {
					res.status(HTTPStatus.INTERNAL_SERVER_ERROR).send('Internal Server Error');
				}
				else {
					res.status(HTTPStatus.OK).send(JSON.stringify(results));
				}
			});	
	});
});

Here we have inserted a node in database through cypher query via REST web service calling.

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


//Cypher Query with Javascript Callback Example

function neo4jQuery(neo4jurl, query, parameters, giveresults) {
	neo4j.connect(neo4jurl, function (err, graph) {
		graph.query(query.join('\n'), {inputusername : 'andrew'} ,function (err, results) {	
			if (err) {
				giveresults(HTTPStatus.INTERNAL_SERVER_ERROR);
			}
			else {
				giveresults(JSON.stringify(results));
			}
		});	
	});
}

//Below is a separation of REST related code and neo4j related code via a javascript callback function

app.route('/allrelations/:username').get(function (req, res){
	res.set({'Content-Type': 'text/json'});
	username = req.params.username;
	parameters = {inputusername : username};
	neo4jQuery(neo4jurl, queryforallrelation, parameters, function(results){
		res.sendStatus(results);
	});
});

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

Above we have taken another  Query Example from Node.js with Query, Parameter and Callback function.

 
// Launch server
app.listen(1212);

We have made the server to listen at 1212 port.

To run the application, we should use – node neo4jtest.js from command shell.

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

Real-time Data update with Angular.js, Node.js and Express.io

We have posted Real-time Data update with Angular.js, Node.js and Socket.io previously.This article is a proof of concept towards make a real time web application with Javascript based Web Server Node.js and Express.IO with Angular.js.The application is same as the previous one ,but this time it is build up with Express.IO.

We have simulated a situation with 4 Product with their Best Buy Price, Best Sell Price and Last Trade Price.

Real-time Data update with Angular.js, Node.js and Express.io

To make this possible, we have selected –

1> Angular.js for client side development – Application Front End

2> Node.js for server side development

3> Express.IO for Server and Client Communication.

4> Node.js Express.IO module extention.

We have created a Proof of Concept with Javascript based web server Node.js, where we have focused on dealing with Express.IO for real time application and angular.js on client side.

Architecture at a glance –

Angular.js NodeJS SocketIO

So here are the steps –

Installation –

A> Download and install Node.js from here.

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

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

Configuration Code –

Now, we will try to describe the code portion –

 
var http = require('http');
var url = require('url');
var fs = require('fs');

// use express.io
express = require('express.io');
var app = express().http().io();

Here we have initialised the http, url and filesystem object within javascript variables in respect of Node.js concept.

Also we have initialised express.io variable in the Node.js Environment.

 
app.get('/angulartableRT.html',function(req,res){
	var path = url.parse(req.url).pathname;
	fs.readFile(__dirname + path, function(err, data){
		if (err){ 
			return send404(res);
		}
		res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'});
		res.write(data, 'utf8');
		res.end();
	});	
});	
....
app.listen(8001);
....

Here, we are giving access to the resources from the node.js server – “angulartableRT.html” for the client browser.

Now the server is listening on port 8001

Reader will get the whole code in GITHUB, which is linked at the end of Post.

Now the most important one is – express.io communication from Node.js. We have commented below the node.js express.io specific code.

 
// define interactions with client
app.io.route('ready', function(req){
    //send data to client
    setInterval(function(){
        
		for(i=0;i// A simulation of data from server instead of database calling
		{
			serverjson[i].BBP = Math.round((parseInt(serverjson[i].BBP) + Math.random())*100)/100;
			serverjson[i].BSP = Math.round((parseInt(serverjson[i].BSP) + Math.random())*100)/100;
			serverjson[i].LTP = Math.round((parseInt(serverjson[i].LTP) + Math.random())*100)/100;
		}
		
		var serverjsonstr = JSON.stringify(serverjson);
		
		req.io.emit('msg', {'msg': serverjsonstr});// Emitting Messages from Server
		req.io.emit('showMsg', {'msgWrite':msgWrite});
    }, 1000);

});

app.io.route('client_data', function (req) {//receiving what sent from client side
	 console.log(req.data.text);//printing cliend data in console
	 msgWrite = req.data.text;
	 app.io.room(req.data.letter).broadcast('showMsg', {//sending back to client 
      'msgWrite':msgWrite,
    });
});

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

Our sample application will be  – http://localhost:8001/
javascriptnosqlbook

Angular.js part –

Below is the code in Angular Controller and the Express.io related code is discussed.

 
/* Controllers */
apps.controller('StockListCtrl', function($scope, express) { 
  $scope.stocks = [];
  express.on('msg', function(data) {// Listening in Socket in Angular Controller
		$scope.stocks = JSON.parse(data.msg);
		//$scope.notes.push(data);
	});
});

//Getting value from server data change event
apps.factory('express', function($rootScope) {
	var express = io.connect();// Connection to the server
	express.emit('ready');
	return {
		on: function(eventName, callback) {// Return callback to the actual function to manipulate it.
			express.on(eventName, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					callback.apply(express, args);
				});
			});
		}
	};
});

Angular HTML Binding

 <script src="http://localhost:8001/socket.io/socket.io.js"></script> // Important to know
 // Access socket.io.js from Angular.js 
.....

Below is the dynamic binding of Angular HTML with the Controller –

<body ng-controller="StockListCtrl">
     <div>
          <table class="table">
                ...
              <tbody>
                   <tr ng-repeat="stock in stocks"> <!-- Dynamic Binding of Angular Template with Data -->
                       <td>{{stock.Product}}</td>
                       <td>{{stock.BBP}}</td>
                       <td>{{stock.BSP}}</td>
                       <td>{{stock.LTP}}</td>
                   </tr>
              </tbody>
          </table>
     </div>
</body>

Reader can download the complete source-code in GitHub.

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

Enter your email address:

Delivered by FeedBurner

Quite the experience to say you’ve done t at least once

Charles Mingus once punched his sax player in the face because he stepped on his solo. Charles Mingus once slammed the heavy wooden key guard down on his pianist fingers. Charles Mingus once got into a knife fight on stage.. Your kids. Talk about the routine changes that come along with the school year. Discuss the concept of a daily mix of exercise, reading, social and family time, school work, and entertainment.

travel backpack anti theft One of the men is seen carrying a black backpack. ET] As of Wednesday night, Boston area hospitals had released 112 of the 178 treated for injuries sustained in the marathon attack. Thirteen patients are in critical condition, the same number as was reported earlier in the day. travel backpack anti theft

anti theft backpack for travel Don feel you have to be too strict with yourself on all the criteria you came up with. “okay, I need 4 levels of difficulty, different styles,. Oh I can pick that Chopin piece because we had Chopin last month,. OK so this is what I still am looking to get. I want to look into hatchet carry that doesn’t cut me or is too hard to draw. But that is why a book or pages printed and laminated are a better use of space. anti theft backpack for travel

anti theft backpack I hope you can see the difference between being armed in a home invasion/liquor store hold up and a mass shooting. The reason it hasn been an issue is due to the rarity of more than one CC holder in a location of a shooting. Hell Vegas there were armed civilians they couldn do shit and resisted even taking out their weapons out of fear of being confused with the shooter.. anti theft backpack

theft proof backpack Generally, you’ll find about 50 bacteria per square inch on a toilet seat that’s the average. While that may sound gross, there are definitely things around your house that are less clean in comparison. Your kitchen sponge, for instance anti theft backpack for travel, has about 10 million bacteria per square inch. theft proof backpack

travel backpack anti theft As an adventurous pollution tourist you can take a bus tour past northern Canada’s strip mines, run by the oil sands companies themselves. On one of these tours, you can check out first hand the now barren mined land that’s bringing tremendous growth and investment into Canada’s oil sands regions Alberta https://www.cheapantitheftbackpack.com/, Canada. Such tours include professionally trained guided tours to an actual oil sands site. travel backpack anti theft

pacsafe backpack I can NEVER get back time with my son. I can imagine having missed this precious first year of his life. I have a calendar full of memories with him that I have recorded while I been home with him. Step 8Pack a toiletries bag of essentials. Many countries in Southeast Asia are unfamiliar with some feminine hygiene products, such as tampons. If you require these on your trip, pack them in your bag. pacsafe backpack

anti theft travel backpack I would do Angel’s Landing in Zion. I know it’s super touristy but I love the hike because of the terrifying heights towards the end. Quite the experience to say you’ve done t at least once. Carr did not respond to a request for comment from The Washington Post, but she told WSB TVthatthe school’s assistant principal called her Thursday to tellher that someone had usedinappropriate language with her 17 year old son. She said her son told her that he and other students were laughing while Hagan was writing an equation on the board. Hagan then began lashing out atCarr’s son. anti theft travel backpack

bobby backpack They only differentiate themselves through low cost but they don’t have a brand image nor build loyalty and if a consumer shops in a different store, they won’t mind getting a different brand. This is not the case with name brands. With name brands, consumers seek the product in any store. bobby backpack

anti theft travel backpack Too many students (and their parents) think of college as the place that will grant them the degree they need to work at X job. The problem is, X job might not exist 10 or 20 years from now. Or X job might be transformed into something else, something that requires critical thinking anti theft backpack, complex reasoning, and writing skills.. anti theft travel backpack

The effect of this magnetic field was to repel the frog, pushing it upwards. When the field was chosen just right (16T), the magnetic repulsion was just enough to offset gravity. As a result, the flog could quite literally levitate in midair.. I been using a SwissGear backpack for the past 5 or so years. It held up well(and just now is maybe looking like it may be time to upgrade/replace as the stretchy stuff on the straps has gone limp). The model I have has long since been discontinued, but hopefully the newer ones will be of the same quality.

anti theft backpack 6) Have you found that after playing Modded Minecraft for several or more years, you can go back? I certainly won There was a time a while ago when I had a world called “Testly 172” (from the name it should be obvious which version it was) where I attempted Vanilla Minecraft. How. The heck anti theft backpack.

Web Application with Highchart.js, Node.js, Express.js and MongoDB(Mongo-JS Module) – Updated for Express 4



HighChart Graph

We previously posted an aricle on Web Application with Highchart.js, Node.js, Express.js (version 3) and MongoDB(Mongo-JS Module).This time we updated that same for Express 4.This application is a of concept towards make a web application for graph generation  with Javascript based Web Server.

In this application we have used following tools and technologies –

1> Node.js for server side development

2> Rest based web service creation with express.js (Express 4)

3> Database – MongoDb

4> Node.js MongoDb Module Extention (mongojs)

5> Highchart.js for Graph generation through Asynchronous call (Ajax)

6> Using Cross-Domain policy to access REST service from Node.js to Ajax Call

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

Our initial code can be downloaded from here.

Architecture at a glance –

HighChartjs NodeJs MongoDB

So here are the steps –

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 (should be connected to internet)

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

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

Server Application

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 = "faodb"; 
var collections = ["seeds"]
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

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


Here we have made the configuration related to express.js
javascriptnosqlbook

Rest Services Code –

 
app.route('/api').get(function (req, res) {
  res.header("Access-Control-Allow-Origin", "*"); // Configuration for Cross-Domain-Policy
  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.route('/getseeddata/:seedname').get(function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    seed = req.params.seedname;
	db.seeds.find({seedname:seed}, function(err, seeds) {
	if( err || !seeds) console.log("No seeds found");
	  else 
	{
		res.writeHead(200, {'Content-Type': 'text/json'});
		seedscollection = seeds[0].seedprice;
		str = '[';
		//console.log(seedscollection);

		seedscollection.forEach( function(seed) {
		   str = str + '{"month":"'+ seed.mmonth + '","price":"'+ seed.price +'"},';
		});
		str = str.substring(0,str.length-1)
		str = str + ']';
		res.end(JSON.stringify(str));
	}
  });
});

Here we have created another REST api to get price information for particular seed from seeds collection and so have done the mongojs query.

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

Now we have to run node appmongodbhighchart.js from command shell to start the node server.

Client Application

Code Explanation for Highchart –

<script type="text/javascript">
    var myAjaxChart;
    var mydata = []; // Javascript Array Declaration
$(document).ready(function () { 

$("#seedselect").change(function() { // On change event of HTML Select Control
    mydata = [];
    requestData($(this).val()); // Parameterised Function calling for Ajax and Highchart Initiation
});

function requestData(data) {
$.ajax({
    url: 'http://localhost:1212/getseeddata/'+data, // Node.js Server REST Call
    type: "GET",
    dataType: "json",
    success: function(seed) {
        var jsonobj = seed;
        var obj = jQuery.parseJSON(jsonobj);
        for(i=0;i<obj.length;i++)
        {
            mydata.push(parseInt(obj[i].price)); // Filling of Array after Ajax Call
        }
        // Initialising the Highchart Object within the success callback
        //Chart
        var options ={
            chart: {
            renderTo: 'container', // Initialising the DIV with Highchart Object
            type: 'line',
            marginRight: 130,
            marginBottom: 25,
         },
         // Other Highchart Properties
         title: {
           text: 'Price Data',
           x: -20 //center
         },
         xAxis: {
         },
         yAxis: {
              title: {
              text: 'Price (Rs)'
         },
         plotLines: [{
              value: 0,
              width: 1,
              color: '#808080'
        }]
     },
     tooltip: {
             valueSuffix: 'Rs'
     },
     legend: {
           layout: 'vertical',
           align: 'right',
           verticalAlign: 'top',
           x: -10,
           y: 100,
           borderWidth: 0
      }
      ,
      series: [{
           name: 'Price',
           data: mydata  // Here the previously populated javascript array will be initialised in data parameter
      }],
     };
     var chardata = new Highcharts.Chart(options);
   },
   cache: false
  });
 }
});

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

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.