Node JS Rest App

Introduction

This blog gives a tutorial on creating a sample REST application using Node.Js, express web framework and MongoDB.

Node.JS

Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications.  Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript. The runtime environment interprets JavaScript using Google’s V8 JavaScript engine. Node.js has an event-driven architecture capable of asynchronous I/O. These design choices aim to optimize throughput and scalability in Web applications with many  input/output operations, as well as for real-time Web applications

ExpressJS

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications, Express provides a thin layer of fundamental web application features, without obscuring Node.js features.

MongoDB

MongoDB is a free and open-source cross-platform document-oriented database. Classified as a NoSQL database, MongoDB avoids the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (it is called BSON in MongoDB), making the integration of data in certain types of applications easier and faster.

Installing Node.Js

 Node.js can be downloaded from this website  and installed. I have installed the Node.js in C:\Applns\Nodejs as shown in the image below

nodeapp

After the installation we have to set the node.js path to the Path Variable and create a new variable called NODE_PATH and it points to {NODEJS_INSTALLATION}\node_modules\npm\node_modules , this is to make the modules available along with Node / npm in any folder.

Non-Blocking IO

We will use the functional programming aspect of Javascript to create non-blocking IO operations. Please refer the sample server application that we can write in nodejs.


/**
* New node file
*/
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});

 In above exampe we can see that app.get() function accepts two input, one is the path as string format ‘/’ and the function to call when a request of root path is called. In short app.get function acts like a router where calling the specific URL , the action mentioned is performed and we need not assign any action object but just a function to it, and the output is not blocked anymore and the function passed acts like a callback function.

Step 1 Install Nodeclipse

You can download nodeclipse from http://www.nodeclipse.org/ which is a node.js development in eclipse.

Step 2 : Create a Node.js Express project

newproj

Create a new project named FirstWeb in the path D:\nodeworkspace\. So the project path is D:\nodeworkspace\FirstWeb

Step 3 : Add dependencies

Create a file package.json  like shown below

{
"name": "FirstWeb",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.12.4",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.12.4",
"jade": "~1.9.2",
"morgan": "~1.5.3",
"serve-favicon": "~2.2.1",
"mongodb": "^1.4.4",
"monk": "^1.0.1"
}
}

The above content explains the dependent modules required for this application.Please note that I have used old version on MongoDB modules as it was only working for me.

Step 4 : Create app.js

You have create app.js which is the starting point of the web app that we are going to build

Following are the sections below

Section 1

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');

Above section declares all the required modules

Section 2 :

var db = monk('localhost:27017/nodetest');

Above is the connection string for the MongoDB. nodetest is the DB name.

Section 3 :

var routes = require('./routes/index');
var rest = require('./routes/rest');
var users = require('./routes/users');

Above is declaration for various “routes” in the app. The web application for the rest app is also included in this code and it uses jade view engine for UI.

Section 4


var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));  //-> __dirname is the path of the node application
app.set('view engine', 'jade');

Above instantiates express app as ‘app’ and sets the view engine.

Section 5

Below code snippet sets the parser and the public or the static content for the application

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

Section 6

Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});

 Section 7

Set the various routes in the app

app.use('/', routes);   //-> Points to index.js
app.use('/rest',rest); //-> The rest app is located in {hostname}/rest
app.use('/users', users); //-> Another URI for users.

 

Section 8

If any request cannot be routed then following happens that denotes 404 error

//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

Section 9

Make the app to listen to port 80

app.listen(80);

Section 10

Below is the last line in the JS file and it is important that should be last line of the code

module.exports = app;

 Rest of the application is described in next post. ->

One thought on “Node JS Rest App

  1. Pingback: Node JS Rest App – 2 | Ganesh's Blog

Leave a Reply

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