JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Node.js : Modularizing Express.js and Node.js Applications

June 9, 2015 by Mohamed Sanaulla Leave a Comment

This tutorial explains how to modullarizing Node.js and Express.js applications. I am using the existing code from my previous post and explaining how to write a modular Node.js applications.

When it comes to writing the modular Node.js applications, there isn’t any one better way to write the modular applications. It comes through your experience and you may encounter different way to re-organize the code and every time it may look better approach for you. In this tutorial, I am going to explain which is better approach from my experience with Express.js and Node.js.

I have shown you how to build RESTful APIs using Express.js and Node.js here. In this post I will show you how we can modularize the code i.e keep related parts of the code in single Javascript file. For example, code dealing with DB can be placed in one javascript file, the code dealing with handling the requests can be placed in another Javascript file.

  • RESTful Example using ExpressJS + Node.js + MongooseJS
  • Mongoose – Node.js + MongoDB with Mongoose Tutorial
  • Book Reference : Web Development with Node and Express

Writing Modular Node.js Applications

I am going to create the following modules from the example in this post:

  1. Application Start point
  2. Database Access Module
  3. Controller module

Basic Introduction to Modularization in Node.js

nodejs-logo

Before I go a bit advanced into modularization of Node.js applications, I would like to take a very simple example to explain the basic concept behind modularizing code in Node.js. I will write a simple calculator app which supports: Addition, Subtraction, Multiplication. I will create a module for doing the calculation and another one which actually runs the application. So there would be 2 Javascript files namely: calculator.js and app.js.

Lets look at the calculator.js:

[code language=”javascript”]
//File name: calculator.js
//Use module.exports to export any function to be available via require()
module.exports.add = function(a,b){return a+b;}
module.exports.subtract = function(a,b){return a-b;}
module.exports.multiply = function(a,b){return a*b;}
[/code]

module is an Object in Node.js used to create Modules. We make the methods in calculator.js available by assigning them to the exports property of module object. We now have a module for performing calculations.

Note: Interesting read about difference between module.exports and exports.

Now lets use this module in our app.js which is the entry point for this simple sample to demonstrate basic concept behind modularity.

[code language=”javascript”]
var calculator = require("./calculator");
console.log("Sum of 4,5: "+ calculator.add(4,5));
console.log("Difference between 4,5: "+ calculator.subtract(4,5));
console.log("Product of 4,5: "+ calculator.multiply(4,5));
[/code]

Executing the above we would see something like below:
Basic Modularity in Node.js

With this basic introduction to Modularity in Node.js let me show you how we can refactor the example in the post: RESTful Example using ExpressJS + Node.js + MongooseJS and modularize it.

Modularizing RESTful Example : Node.js Application

As stated at the beginning there would be a module for DB related code, a module for controller operations and then an application starting point. The directory structure of the sample looks like below:
Node Modularity Directory Structure

Install the required packages i.e express, body-parser, mongoose using the command npm install express body-parser mongoose --save.

The code for the book_dao.js is as given below:

[code language=”javascript”]
//Filename: book_dao.js
//mongoose is used for interacting with MongoDB
var mongoose = require(‘mongoose’);

var dbHost = ‘mongodb://localhost:27017/test’;
mongoose.connect(dbHost);
//Create a schema for Book
var bookSchema = mongoose.Schema({
name: String,
//Also creating index on field isbn
isbn: {type: String, index: true},
author: String,
pages: Number
});

//Create a Model by using the schema defined above
//Optionally one can provide the name of collection where the instances
//of this model get stored. In this case it is "mongoose_demo". Skipping
//this value defaults the name of the collection to plural of model name i.e books.
var Book = mongoose.model(‘Book’, bookSchema);

//Connecting to Mongod instance.
mongoose.connection;

module.exports.findOne = function(isbn, callback){
Book.findOne({isbn: isbn}, function(err, result){
if ( err ) throw err;
callback(result);
});
}

module.exports.findAll = function(callback){
Book.find({}, function(err, result){
if ( err ) throw err;
callback(result);
});
}

module.exports.addNewBook = function(body, callback){
var book = new Book({
name:body.name,
isbn: body.isbn,
author: body.author,
pages: body.pages
});

//Saving the model instance to the DB
book.save(function(err, result){
if ( err ) throw err;
callback({
messaage:"Successfully added book",
book:result
});
});
}

module.exports.editBook = function(body, isbn, callback){
Book.findOne({isbn: isbn}, function(err, result){
if ( err ) throw err;

if(!result){
callback({
message:"Book with ISBN: " + isbn+" not found.",
});
}

result.name = body.name;
result.isbn = body.isbn;
result.author = body.author;
result.pages = body.pages;

result.save(function(err, result){
if ( err ) throw err;
callback({
message:"Successfully updated the book",
book: result
});
});

});
}

module.exports.deleteBook = function(isbn, callback){
Book.findOneAndRemove({isbn: isbn}, function(err, result){
callback({
message: "Successfully deleted the book",
book: result
});
});
}
[/code]

From the above code you can see that the book_dao.js depends only on the Mongoose API.

The code for book_controller.js is as given below:

[code language=”javascript”]
var bookDao = require("./book_dao");

module.exports.getBookDetails = function(params, callback){
console.log("Fetching details for book with ISBN: " + params.isbn);
bookDao.findOne(params.isbn, callback);
}

module.exports.getAllBooks = function(callback){
console.log("Fetching all books");
bookDao.findAll(callback);
}

module.exports.addNewBook = function(body, callback){
console.log("Adding new book");
bookDao.addNewBook(body, callback);
}

module.exports.editBook = function(body, isbn, callback){
console.log("Editing Book");
bookDao.editBook(body, isbn, callback);
}
module.exports.deleteBook = function(isbn, callback){
console.log("Deleting book");
bookDao.deleteBook(isbn, callback);
}
[/code]

The code for routes.js is given below:

[code language=”javascript”]
var bookController = require("./book_controller");

module.exports = function(app){
//Get the details of the book with the given isbn
app.get(‘/book/:isbn’, function(req, res){
bookController.getBookDetails(req.params, function(results){res.json(results);});
});

//Get all the books
app.get(‘/book’, function(req, res){
bookController.getAllBooks(function(results){res.json(results);});
});

app.post(‘/book’, function(req, res){
bookController.addNewBook(req.body, function(results){
res.json(results);
});
});

app.put(‘/book/:isbn’, function(req, res){
bookController.editBook(req.body, req.params.isbn, function(results){
res.json(results);
});
});

app.delete(‘/book/:isbn’, function(req, res){
bookController.deleteBook(req.params.isbn, function(results){
res.json(results);
});
});
}
[/code]

routes.js is responsible for mapping the URLs to the methods in the controller.

From above code its clear that book_dao.js depends only on Mongoose, book_controller.js depends only on the book_dao.js and routes.js depends only on book_controller.js

Running Modular Node.js Example Application

The below is the code for app.js which is the starting point for our application or in other words the place where the server is initiated and launched.

[code language=”javascript”]
//Filename: app.js
//Express is required for creating Node.js based web apps
var express = require(‘express’);

//body-parser is used to parse the Request body and populate the req.
var bodyParser = require(‘body-parser’);

var app = express();
app.set(‘port’, 3300);

//Configuring Express App to make use of BodyParser’s JSON parser to parse
//JSON request body
app.use(bodyParser.json());

//Including the routes module
var routes = require("./lib/routes");
routes(app);

//Starting up the server on the port: 3300
app.listen(app.get(‘port’), function(){
console.log(‘Server up: http://localhost:’ + app.get(‘port’));
});
[/code]

The above app.js depends on routes.js to setup the routes and controller binding.

Lets run the above sample as shown below:

[code language=”shell”]
G:\node\testapp\modular_sample_2>node app.js
Server up: http://localhost:3300
[/code]

The code for this sample can be found in the github as well.

  • RESTful Example using ExpressJS + Node.js + MongooseJS
  • Mongoose – Node.js + MongoDB with Mongoose Tutorial
  • Book Reference : Web Development with Node and Express

I hope this tutorial helped you to understand how to modularize a Node.js application. This tutorial used RESTful example from our previous tutorials. Note that there is no one rule for modularizing the code, it can be improvized based on your experience. If you have any questions on writing the modular Node.js applications, please write it in the comments section.

Filed Under: ExpressJS, NodeJS Tagged With: NodeJS Tutorials

Node.js : Packaging and Deploying Node.js Applications [COMPLETE GUIDE]

June 4, 2015 by Mohamed Sanaulla Leave a Comment

In this tutorial I am going to explain you how to use the Node Package Manager (NPM) to package and deploy your own Node.js application. I assume that you have already installed the Node.js and NPM in your local system to run this example.

  • Simple Steps to Install Node.js and NPM on Windows

In my previous post I showed you how to authenticate with Twitter and also make use of Twitter API to retrieve tweets. I have made use of several Node packages to achieve what I intended to. But what if someone wants to take the source code and run it in their machine? For example one of the readers have copied the source code and they now just want to run the application without knowing what all dependencies are there from the code and then installing them individually. Is this even possible in Node.js? Is there something like Maven where in we just mention the dependencies and the mvn automatically downloads the dependencies and can also launch the application.

nodejs-logo

The answer for the above questions is Yes, the solution for the above problmes is the Node Package Manager(NPM). Just like maven can host libraries which are reused in applications, even NPM can host libraries which are reused in your Node.js applications. NPM comes bundled with Node.js, so you can download Node.js from here and install it to also get NPM.

  • RESTful Example using ExpressJS + Node.js + MongooseJS
  • Mongoose – Node.js + MongoDB with Mongoose Tutorial
  • Book Reference : Web Development with Node and Express

Now let us pick the sample app developed in this post, and create a deployable package which any user can download and run it in his environment.

The following Node packages are used in that sample app:

  1. express
  2. express-handlebars
  3. request
  4. querystring

Creating an Empty Node.js Code Base

I am creating a new directory by name: node_packaging and in that directory execute the following command:

[code language=”shell”]
npm init
[/code]

When you run the above command, after that it will ask you a series of questions (just like when you are initializing project using maven). The series of questions are asked so as to create and populate a new package.json file (think of it as your pom.xml in maven). If you want to know more about package.json and its attributes, visit here. The below is how it looks after initializing using NPM. Look at the below screen and input the answers which shown in the screenshot. These values are used by the NPM to create a package.json file.

NPM Init

After that you can see a file by name package.json created with the following content:

[code language=”javascript”]
{
"name": "node-packaging-demo",
"version": "1.0.0",
"description": "Demo to show node packaging",
"main": "social_signin.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
[/code]

I can edit/update the package.json, for example add the author details as shown below:

[code language=”javascript”]
{
"name": "node-packaging-demo",
"version": "1.0.0",
"description": "Demo to show node packaging",
"main": "social_signin.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mohamed Sanaulla",
"license": "ISC"
}
[/code]

Adding Dependencies using NPM

All the dependencies of the application are declared in package.json. One either edit the file directly or make use of the npm tool to update the dependencies in package.json. The below code adds the required dependencies to our app:

[code language=”shell”]
npm install –save express express-handlebars request querystring
[/code]

The above command along with installing the mentioned packages, adds them as a dependency in pakcage.json. Let us now look at the contents of package.json:

[code language=”javascript” highlight=”11-16″]
{
"name": "node-packaging-demo",
"version": "1.0.0",
"description": "Demo to show node packaging",
"main": "social_signin.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mohamed Sanaulla",
"license": "ISC",
"dependencies": {
"express": "^4.12.4",
"express-handlebars": "^2.0.1",
"querystring": "^0.2.0",
"request": "^2.57.0"
}
}
[/code]

In the above the highlighted lines are the dependencies of our application and the number against it is the version of the package we are using. If no version is mentioned while executing npm install --save then the latest in NPM repository is used.

And when you list the files in your project folder you would see a folder by name node_modules. This is where all your modules get downloaded to.

nodemodules

nodemodules1

Building the Node.js Application

The below is the directory structure of the application:

[code]
|–social_signin.js
|–views
|–home.handlebars
|–my.handlebars
|–layouts
|–main.handlebars
[/code]

This directory structure is relative to the directory we created first i.e node_packaging.

Following is the source code of our application

File: social_signin.js

[code language=”javascript”]
//FileName: social_signin.js
var express = require(‘express’);

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require(‘express-handlebars’);

//NPM Module to make HTTP Requests
var request = require("request");

//NPM Module To parse the Query String and to build a Query String
var qs = require("querystring");

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine(‘handlebars’, exphbs({defaultLayout: ‘main’}));
app.set(‘view engine’, ‘handlebars’);

//URL To obtain Request Token from Twitter
var requestTokenUrl = "https://api.twitter.com/oauth/request_token";

//To be obtained from the app created on Twitter
var CONSUMER_KEY = "GET_IT_FROM_TWITTER";
var CONSUMER_SECRET = "GET_IT_FROM_TWITTER";

//Oauth Object to be used to obtain Request token from Twitter
var oauth = {
callback : "http://localhost:3000/signin-with-twitter",
consumer_key : CONSUMER_KEY,
consumer_secret : CONSUMER_SECRET
}
var oauthToken = "";
var oauthTokenSecret = "";
app.get(‘/’, function (req, res) {
//Step-1 Obtaining a request token
request.post({url : requestTokenUrl, oauth : oauth}, function (e, r, body){

//Parsing the Query String containing the oauth_token and oauth_secret.
var reqData = qs.parse(body);
oauthToken = reqData.oauth_token;
oauthTokenSecret = reqData.oauth_token_secret;

//Step-2 Redirecting the user by creating a link
//and allowing the user to click the link
var uri = ‘https://api.twitter.com/oauth/authenticate’
+ ‘?’ + qs.stringify({oauth_token: oauthToken})
res.render(‘home’, {url : uri});
});

});

//Callback to handle post authentication.
app.get("/signin-with-twitter", function(req, res){
var authReqData = req.query;
oauth.token = authReqData.oauth_token;
oauth.token_secret = oauthTokenSecret;
oauth.verifier = authReqData.oauth_verifier;

var accessTokenUrl = "https://api.twitter.com/oauth/access_token";
//Step-3 Converting the request token to an access token
request.post({url : accessTokenUrl , oauth : oauth}, function(e, r, body){
var authenticatedData = qs.parse(body);
console.log(authenticatedData);

//Make a request to get User’s 10 latest tweets
var apiUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json" + "?"
+ qs.stringify({screen_name: authenticatedData.screen_name, count: 10});

var authenticationData = {
consumer_key : CONSUMER_KEY,
consumer_secret : CONSUMER_SECRET,
token: authenticatedData.oauth_token,
token_secret : authenticatedData.oauth_token_secret
};

request.get({url : apiUrl, oauth: authenticationData, json:true}, function(e, r, body){

var tweets = [];
for(i in body){
var tweetObj = body[i];
tweets.push({text: tweetObj.text});
}

var viewData = {
username: authenticatedData.screen_name,
tweets: tweets
};

res.render("my", viewData);

});

});
});

app.listen(3000, function(){
console.log(‘Server up: http://localhost:3000’);
});
[/code]

File Name: main.handlebars

[code language=”html”]
<!– FileName: main.handlebars–>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>
[/code]

File Name: home.handlebars

[code language=”html”]
<!– FileName: home.handlebars–>
<h1>SignIn With Twitter Sample</h1>

<a href="{{url}}">Signin with Twitter</a>
[/code]

File Name: my.handlebars

[code language=”html”]
<!– FileName: my.handlebars–>
<h1>Welcome {{username}} </h1>
<h3>Your tweets</h3>
<ul>
{{#tweets}}
<li>{{text}}</li>
{{/tweets}}
</ul>
[/code]

Running the Node.js Sample Application

[code]
G:\node\node_packaging>node social_signin.js
Server up: http://localhost:3000
[/code]

Navigating to http://localhost:300 gives use a page with “Sign with Twitter” link. Clicking on it shows us the latest 10 tweets.

Nodejs Server Up

Twitter Signin Nodejs

Pushing the code to Github

Now I am going to push the code to Github and then show you how packaging using NPM and package.json helps in sharing the application among other developers. Before carrying out the below task, install Git on your machine.

Carry out the following steps to push the code to github:

    1. Create a new repository on github.com
    2. Run git init in your project folder to initialize a new git repository locally.
    3. Run git status in your project folder, you will see the following output:

      [code language=”shell”]
      $ git status
      On branch master

      Initial commit

      Untracked files:
      (use "git add <file>…" to include in what will be committed)

      node_modules/
      package.json
      social_signin.js
      views/

      nothing added to commit but untracked files present (use "git add" to track)
      [/code]

      We need to remove node_modules folder from getting committed to Github. So we create a new .gitignore file in the project root folder i.e in node_packaging folder. The content of .gitignore file is:

      [code]
      $ cat .gitignore
      node_modules
      [/code]

      Run git status again, this time you will see that the node_modules folder is not listed in the files to be committed:

      [code]
      $ git status
      On branch master

      Initial commit

      Untracked files:
      (use "git add <file>…" to include in what will be committed)

      .gitignore
      package.json
      social_signin.js
      views/

      nothing added to commit but untracked files present (use "git add" to track)
      [/code]

    4. Add the Github repository you created in Step-1 as a remote repository to the local repository you created in Step-2. This can be done using the following command: git remote add origin GITHUB_REPO_URL. You can get the GITHUB_REPO_URL from GitHub Repository page you created in Step-1
    5. Now commit and push your changes to the Github repository. It can be done as follows:

      [code]
      $ git add -A
      $ git commit
      $ git push origin master
      [/code]

Now the code should be available in your Github repository. Mine is at: https://github.com/sanaulla123/nodejs-package-demo

Advantage of Node.js Packaging

So we have setup everything for any developer to just clone the Github repository and start running the application locally. Let us also try to clone the repository in another location and see if this packaging really works!!

[code language=”shell”]
Mohamed@SANA-LAPTOP /g/node/node_packaging (master)
$ cd ..

Mohamed@SANA-LAPTOP /g/node
$ mkdir node_packaging_clone

Mohamed@SANA-LAPTOP /g/node
$ cd node_packaging_clone/

#Cloning the Github repository
Mohamed@SANA-LAPTOP /g/node
$ git clone https://github.com/sanaulla123/nodejs-package-demo.git

Mohamed@SANA-LAPTOP /g/node/node_packaging_clone
$ ls
nodejs-package-demo

Mohamed@SANA-LAPTOP /g/node/node_packaging_clone
$ cd nodejs-package-demo/

#There is no node_modules folder!!
Mohamed@SANA-LAPTOP /g/node/node_packaging_clone/nodejs-package-demo (master)
$ ls
package.json social_signin.js views

#This command picks up the dependencies from package.json and installs them to the local project folder.
Mohamed@SANA-LAPTOP /g/node/node_packaging_clone/nodejs-package-demo (master)
$ npm install

#The node_modules folder got created after the above command.
Mohamed@SANA-LAPTOP /g/node/node_packaging_clone/nodejs-package-demo (master)
$ ls
node_modules package.json social_signin.js views
[/code]

Now you should be able to run the application as before. This was a small introduction to packaging your node.js applications. Hope you found it easy to understand and beneficial. If you have any questions on Node.js Application Packaging, please write it in the comments section. Enjoy reading more tutorials about Node.js in our blog.

Filed Under: ExpressJS, NodeJS Tagged With: NodeJS Tutorials

Express.js + Bootstrap : Web Application Development Tutorial

June 2, 2015 by Mohamed Sanaulla Leave a Comment

In the last few posts we saw about created REST API, Authenticating with Twitter using Express.js. In this post lets see how we can create Web Applications by making use of Bootstrap CSS Framework with Express.js. If you are interested in learning Bootstrap framework, please read our extensive tutorials on bootstrap CSS framework. Also read this tutorial to setup the bootstrap environment in your local system.

Express is a leading web application framework for developing web application using the Node.js packages. It is easy to install using npm and get started with simple applications.

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.

This tutorial is a simple step-by-step guide for developing a web application using the Express.js and Bootstrap as the UI framework.

  • Bootstrap vs Foundation

Web Application Development with Express.js + Bootstrap

express

Serving Static files from Express.js

  • Book Reference : Web Development with Node and Express

Lets look at how we can serve static files i.e your CSS, Javascript and Image files from Express.js server. Express provides a special middleware express.static for this. We pass the root directory containing the static files to the express.static middleware. We can also bind an URL to this root directory (Also Read : Serving static files in Express). The below code shows this integrations:

[code language=”javascript”]
var express = require(‘express’);

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require(‘express-handlebars’);

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine(‘handlebars’, exphbs({defaultLayout: ‘main’}));
app.set(‘view engine’, ‘handlebars’);

//Defining middleware to serve static files
app.use(‘/static’, express.static(‘public’));
[/code]

The static files i.e CSS, Javascript and Image files would be placed under the public folder.

Lets look at creating some view templates.

Layout Template using Bootstrap

Generally there will be a layout template or a base template that defines the headers, footers, CSS linking, Javascript linking and this layout/base template is reused by all other view templates OR in other words the base template includes the output from all other view templates.

As we would be using Bootstrap, you would have to download Bootstrap related CSS, Javascript, Images and other static files. You can download it from here.

The below is our directory structure for this example:

[code]
|–express_bootstrap.js
|–public
|–css
|–fonts
|–js
|–views
|–home.handlebars
|–layouts
|–main.handlebars
[/code]

The contents of the public folder above are the contents from the downloaded bootstrap files.

The code for main.handlebars is given below. Please read our previous article about twitter login which explains how to use the handlebars template engine.:

[code language=”html”]
<!– Filename: main.handlebars –>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/css/bootstrap.css" media="screen" charset="utf-8">
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
<div class="container">
{{{body}}}
</div>
<script src="/static/js/jquery.js" charset="utf-8"></script>
<script src="/static/js/bootstrap.js" charset="utf-8"></script>
</body>
</html>
[/code]

You can see above how the CSS and Javascript files from the Bootstrap are configured above. Also observe the URL of the static files is starting with /static, this is how we have defined in our express.js middleware.

Creating one of the view templates using Bootstrap

twitter bootstrap

Now we need to create one view template which will be used by our Node.js application. The template name is home.handlebars and below is the code for it:

[code language=”html”]
<div class="row">
<div class="col-md-12">
<h1>Home</h1>
</div>
</div>

<div class="row">
<div class="col-md-4">
<p>This is Column 1</p>
</div>
<div class="col-md-4">
<p>
This is Column 2
</p>
</div>
<div class="col-md-4">
<p>
This is Column 3
</p>
</div>
</div>
[/code]

You can see above that I am making use of CSS Classes from Bootstrap.

Express.js Server

Now let us see how we can write the express.js code to render the above created template home.handlebars, then configure express.js middleware to serve static files in our public folder.

[code language=”javascript”]
//Filename: express_bootstrap.js
var express = require(‘express’);

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require(‘express-handlebars’);

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine(‘handlebars’, exphbs({defaultLayout: ‘main’}));
app.set(‘view engine’, ‘handlebars’);

//Defining middleware to serve static files
app.use(‘/static’, express.static(‘public’));

app.get("/home", function(req, res){
res.render("home")
});

app.listen(3000, function(){
console.log(‘Server up: http://localhost:3000’);
});
[/code]

Running the above server using the command node express_bootstrap.js spawns server on port 3000. Navigating to http://localhost:3000/home shows up a web page something like below:

Summary

This tutorial helps you to understand the basic concepts on building a simple web application using Express.js and Bootstrap frameworks. Note that this may not help you to build a large scale projects, but this is the fundamental building blocks to learn about ExpressJS framework and Bootstrap integration. If you are looking for how to integrate Express.js (ExpressJS) and Bootstrap, then this tutorial would help you. If you have any questions, please write it in the comments section.

Book Reference : Web Development with Node and Express

Filed Under: Bootstrap, ExpressJS, NodeJS Tagged With: NodeJS Tutorials

HOW TO : SignIn with Twitter using Node.js and Express.js

June 1, 2015 by Mohamed Sanaulla Leave a Comment

In my previous posts, I have explained about few of the topics on NodeJS web application framework ExpressJS. Please read the topics: REST using ExpressJS, Working with MongooseJS and CRUD operations using MongoDB and NodeJS.

This post uses various combination on frameworks and shows you how to SignIn with Twitter using Node.js and Express.js frameworks. Accessing the social network websites like twitter and facebook through framework APIs become one of the important programming activities to implement the user actions in the websites. I have tried the template framework HandlebarsJS which is similar to another popular template framework Mustache in this example.

In this post I am going to show you few interesting things:

  1. Integrating Handlebars templates in Express.js
  2. Implemeting SignIn With Twitter
  3. Retrieving User’s latest 10 tweets after signin with Twitter

I am using the following new Node packages for this tutorial:

  1. express-handlebars: Node package to integrate Handlebars template engine with Express.js
  2. request: This package simplifies making HTTP request from the application. Node comes with default package for making HTTP requests, but I am making use of this as it provides support for OAuth Request signing. This OAuth request signing is required while authenticating with Twitter as we will see futher.
  3. querystring: This package helps in parsing the query strings into JSON objects and creating query string out of the JSON objects.

If you are interested in learning Node.js framework, please consider purchasing the below books for further reference:

  • Professional Node.js
  • Node.js in Action
  • Node.js Receipes

HandlebarsJS and ExpressJS Integration

HandlebarsJS is a templating framework which is used to generate dynamic views.

The below code sets up the Handlebars with ExpressJS:

[code language=”javascript”]
//File Name: handlebars_demo.js
var express = require(‘express’);

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require(‘express-handlebars’);

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine(‘handlebars’, exphbs({defaultLayout: ‘main’}));
app.set(‘view engine’, ‘handlebars’);

app.get(‘/’, function (req, res) {
//Use hello.handlebars template with the JSON data passed as another argument
res.render("hello", {name : "Sanaulla"});
});

app.listen(3000, function(){
console.log(‘Server up: http://localhost:3000’);
});
[/code]

We need to create a HandlebarsJS template which is shown below:

[code language=”html”]
//hello.handlebars
<h1>Hello Mr. {{name}} from Handlebars </h1>
[/code]

We also create a layout file by name main.handlebars as shown below:

[code language=”html”]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>
[/code]

The above layout wraps any of the template output which means in this case the output of hello.handlebars replaces the {{{body}}}

The way the files are arranged is as shown below

[code]
node_samples
|–handlebars_demo.js
|–views
|–hello.handlebars
|–layouts
|–main.handlebars
[/code]

Now let us run the above javascript by using the command:

[code]
node handlebars_demo.js
[/code]

Now open the following URL in your browser: http://localhost:3000/.

You will see Hello Mr. Sanaulla from Handlebars printed on the browser.

With this we have tried introduction to HandlebarsJS let us proceed to see how we can integrate with Twitter.

Implementing SignIn With Twitter using ExpressJS

The documentation here provides the different steps to authenticate with Twitter. Though the documentation is clear enough but its difficult to create a working solution following the official documentation.

Authenticating with Twitter involves 3 steps:

  1. Step-1: Obtaining a request token
  2. Step-2: Authenticating the user by redirecting to Twitter
  3. Step-3: Converting the request token to an access token

For the rest of the tutorial, the following code is common:

[code language=”javascript”]
//File Name: social_signin.js
var express = require(‘express’);

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require(‘express-handlebars’);

//NPM Module to make HTTP Requests
var request = require("request");

//NPM Module To parse the Query String and to build a Query String
var qs = require("querystring");

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine(‘handlebars’, exphbs({defaultLayout: ‘main’}));
app.set(‘view engine’, ‘handlebars’);
[/code]

Before starting off, you need to create an application on Twitter. After creating the app, you will have access to Consumer Key and Consumer Secret which is a must to authenticate with Twitter.

Step-1 : Obtaining the request token

In this tutorial, I obtain the request token on loading the page and use that request token to build the URL to Sign In With Twitter.

The below code makes call to Twitter to get request token.

[code language=”javascript”]
//URL To obtain Request Token from Twitter
var requestTokenUrl = "https://api.twitter.com/oauth/request_token";

//To be obtained from the app created on Twitter
var CONSUMER_KEY = "kuDm1KBKBJH3PpusFxcAA";
var CONSUMER_SECRET = "5wOFqJe4R0Kf6SV9tXuqrzkpD7t7d8cvwZhPC7TW8";

//Oauth Object to be used to obtain Request token from Twitter
var oauth = {
callback : "http://localhost:3000/signin-with-twitter",
consumer_key : CONSUMER_KEY,
consumer_secret : CONSUMER_SECRET
}
var oauthToken = "";
var oauthTokenSecret = "";
app.get(‘/’, function (req, res) {
//Step-1 Obtaining a request token
request.post({url : requestTokenUrl, oauth : oauth}, function (e, r, body){

//Parsing the Query String containing the oauth_token and oauth_secret.
var reqData = qs.parse(body);
oauthToken = reqData.oauth_token;
oauthTokenSecret = reqData.oauth_token_secret;

//Step-2 Redirecting the user by creating a link
//and allowing the user to click the link
var uri = ‘https://api.twitter.com/oauth/authenticate’
+ ‘?’ + qs.stringify({oauth_token: oauthToken})
res.render(‘home’, {url : uri});
});

});
app.listen(3000, function(){
console.log(‘Server up: http://localhost:3000’);
});
[/code]

The code for the template home.handlebars is given below:

[code language=”html”]
<h1>SignIn With Twitter Sample</h1>

<a href="{{url}}">Signin with Twitter</a>
[/code]

Another template file main.handlebars is same as given above while introducing to Handlebars.

The directory structure is as given below:

[code]
|–social_signin.js
|–views
|–home.handlebars
|–layouts
|–main.handlebars
[/code]

Lets run the above code by running node social_signin.js. This starts the server on port 3000.

Navigate to http://localhost:3000/, you should see the below output:

In the above screenshot the link Signin With Twitter redirects the user to Twitter to authenticate the user and authorise the app to make requests on behalf of the user. The request token obtained in this step is passed along with this link.

Step-2 Authenticating the user by redirecting to Twitter

There is nothing much to be done in the code in this step. The link genereted in the above step redirects the user to Twitter to authenticate and authorise.

And the callback we had sent earlier is invoked on successfully authenticating on Twitter.

The following data is sent to our callback: oauth_token and oauth_verifier.

Step-3 Converting the request token to an access token

In the callback we make use of the oauth_token and oauth_verifier to get the access token by making a oauth signed POST call to the URL: https://api.twitter.com/oauth/access_token

In the POST response after verifying the tokens and authenticating the user we get the oauth_token_secret, user_id, screen_name of the authenticated user.

The below code handles the Step-3:

[code language=”javascript”]
//Callback to handle post authentication.
app.get("/signin-with-twitter", function(req, res){
var authReqData = req.query;
oauth.token = authReqData.oauth_token;
oauth.token_secret = oauthTokenSecret;
oauth.verifier = authReqData.oauth_verifier;

var accessTokenUrl = "https://api.twitter.com/oauth/access_token";
//Step-3 Converting the request token to an access token
request.post({url : accessTokenUrl , oauth : oauth}, function(e, r, body){
var authenticatedData = qs.parse(body);
console.log(authenticatedData);
});
});
[/code]

With this we have successfully authenticated with twitter. Now let us see how to retrieve latest 10 tweets of the user.

Retrieving User’s latest 10 tweets after signin with Twitter

We make use of the oauth_token and oauth_token_secret along with the consumer_key and consumer_secret while making a call to the twitter API. The below code invokes the Twitter API with the right authentication data.

[code language=”javascript”]

//Make a request to get User’s 10 latest tweets
var apiUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json" + "?"
+ qs.stringify({screen_name: authenticatedData.screen_name, count: 10});

var authenticationData = {
consumer_key : CONSUMER_KEY,
consumer_secret : CONSUMER_SECRET,
token: authenticatedData.oauth_token,
token_secret : authenticatedData.oauth_token_secret
};

request.get({url : apiUrl, oauth: authenticationData, json:true}, function(e, r, body){

var tweets = [];
for(i in body){
var tweetObj = body[i];
tweets.push({text: tweetObj.text});
}

var viewData = {
username: authenticatedData.screen_name,
tweets: tweets
};

res.render("my", viewData);

});
[/code]

Wrapping Up

The directory structure for this sample is:

[code]
|–social_signin.js
|–views
|–home.handlebars
|–my.handlebars
|–layouts
|–main.handlebars
[/code]

The complete code for this sample is:

[code language=”javascript”]
//FileName: social_signin.js
var express = require(‘express’);

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require(‘express-handlebars’);

//NPM Module to make HTTP Requests
var request = require("request");

//NPM Module To parse the Query String and to build a Query String
var qs = require("querystring");

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine(‘handlebars’, exphbs({defaultLayout: ‘main’}));
app.set(‘view engine’, ‘handlebars’);

//URL To obtain Request Token from Twitter
var requestTokenUrl = "https://api.twitter.com/oauth/request_token";

//To be obtained from the app created on Twitter
var CONSUMER_KEY = "kuDm1KBKBJH3PpusFxcAA";
var CONSUMER_SECRET = "5wOFqJe4R0Kf6SV9tXuqrzkpD7t7d8cvwZhPC7TW8";

//Oauth Object to be used to obtain Request token from Twitter
var oauth = {
callback : "http://localhost:3000/signin-with-twitter",
consumer_key : CONSUMER_KEY,
consumer_secret : CONSUMER_SECRET
}
var oauthToken = "";
var oauthTokenSecret = "";
app.get(‘/’, function (req, res) {
//Step-1 Obtaining a request token
request.post({url : requestTokenUrl, oauth : oauth}, function (e, r, body){

//Parsing the Query String containing the oauth_token and oauth_secret.
var reqData = qs.parse(body);
oauthToken = reqData.oauth_token;
oauthTokenSecret = reqData.oauth_token_secret;

//Step-2 Redirecting the user by creating a link
//and allowing the user to click the link
var uri = ‘https://api.twitter.com/oauth/authenticate’
+ ‘?’ + qs.stringify({oauth_token: oauthToken})
res.render(‘home’, {url : uri});
});

});

//Callback to handle post authentication.
app.get("/signin-with-twitter", function(req, res){
var authReqData = req.query;
oauth.token = authReqData.oauth_token;
oauth.token_secret = oauthTokenSecret;
oauth.verifier = authReqData.oauth_verifier;

var accessTokenUrl = "https://api.twitter.com/oauth/access_token";
//Step-3 Converting the request token to an access token
request.post({url : accessTokenUrl , oauth : oauth}, function(e, r, body){
var authenticatedData = qs.parse(body);
console.log(authenticatedData);

//Make a request to get User’s 10 latest tweets
var apiUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json" + "?"
+ qs.stringify({screen_name: authenticatedData.screen_name, count: 10});

var authenticationData = {
consumer_key : CONSUMER_KEY,
consumer_secret : CONSUMER_SECRET,
token: authenticatedData.oauth_token,
token_secret : authenticatedData.oauth_token_secret
};

request.get({url : apiUrl, oauth: authenticationData, json:true}, function(e, r, body){

var tweets = [];
for(i in body){
var tweetObj = body[i];
tweets.push({text: tweetObj.text});
}

var viewData = {
username: authenticatedData.screen_name,
tweets: tweets
};

res.render("my", viewData);

});

});
});

app.listen(3000, function(){
console.log(‘Server up: http://localhost:3000’);
});
[/code]

[code language=”html”]
<!– FileName: main.handlebars–>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>
[/code]

 

[code language=”html”]
<!– FileName: home.handlebars–>
<h1>SignIn With Twitter Sample</h1>

<a href="{{url}}">Signin with Twitter</a>
[/code]

 

[code language=”html”]
<!– FileName: my.handlebars–>
<h1>Welcome {{username}} </h1>
<h3>Your tweets</h3>
<ul>
{{#tweets}}
<li>{{text}}</li>
{{/tweets}}
</ul>
[/code]

If you are interested in learning Node.js framework, please consider purchasing the below books for further reference:

  • Professional Node.js
  • Node.js in Action
  • Node.js Receipes

Filed Under: ExpressJS, NodeJS Tagged With: JavaScript Tutorials

RESTful Example using ExpressJS + Node.js + MongooseJS

May 18, 2015 by Mohamed Sanaulla Leave a Comment

RESTful Web Services Example : ExpressJS + Node.js + MongooseJS

In my previous articles I have explaines about CRUD operations Node.js + MongoDB – Performing CRUD Operations and Mongoose – Node.js + MongoDB with Mongoose Tutorial. In this post I will show you how to create CRUD operations using RESTful Web Services and ExpressJS with MongooseJS. I would be using the following 3 Node packages for this sample namely:

  1. ExpressJS
  2. body-parser
  3. MongooseJS

ExpressJs

From the Node Package manager website:

Fast, unopinionated, minimalist web framework

Express is used to create Web applications using Node.js. It provides support for routes, setting up view templates and others. This is most popular Node.js web framework as of now. The advantage of using ExpressJS is to reduce the time and lines of code written unless using the plain Node.js modules.

Body-parser

From the Node Package manager wwebsite:

Node.js body parsing middleware.

This middleware is used for intercepting the requests, parsing the request body and then populating it in the node.js’s req object.

MongooseJS

From the Node Package Manager website:

MongooseJS is a MongoDB object modeling tool designed to work in an asynchronous environment.

This is used to define Model objects and then use it to interact with MongoDB, a kind of ORM in the OO Programming world. MongooseJS is a Object Data Mapping (ODM) for JavaScript frameworks. This helps you to map the JavaScript objects to the MongoDB database. This tool is developed and maintained by the MongoDB community itself.

enm

Defining the RESTful API

In this tutorial I am going to implement a simple RESTful Web Services (Read : Spring REST Web Services) example using ExpressJS ,Node.js and MongooseJS. The right below section just defines the list of operations that are going to implemented as part of the excersise. The list of RESTful APis are :

  • Fetch list of all books in the system : GET /book/
  • Fetch details of a book in the system : GET /book/:isbn
  • Add a new book to the system : POST /book/
  • Edit details of existing book in the system : PUT /book/:isbn
  • Delete given book from the system : DELETE /book/:isbn

1. Fetch list of all books in the system : GET /book/
Parameters: No parameters
Response: The response is going to be an array of JSON objects (Also Read : What is JSON?) with the structure given below.

[code language=”javascript”]
[
{
"_id":STRING,
"name":STRING,
"isbn":STRING,
"author":STRING,
"pages":INTEGER,
"_v":STRING
}
]
[/code]

2. Fetch details of a book in the system : GET /book/:isbn
Parameters: ISBN of the book
Response: The response is going to be the JSON object with the structure given below.

[code language=”javascript”]
{
"_id":STRING,
"name":STRING,
"isbn":STRING,
"author":STRING,
"pages":INTEGER,
"_v":STRING
}
[/code]

3. Add a new book to the system : POST /book/
Parameters: Data of following format has to be sent in the request body

[code language=”javascript”]
{
"name":STRING,
"isbn":STRING,
"author":STRING,
"pages":INTEGER
}
[/code]

Response: The response is going to be the JSON object with the structure given below.

[code language=”javascript”]
{
"messaage": "Successfully added book",
"book": {
"__v": STRING,
"name": STRING,
"isbn": STRING,
"author": STRING,
"pages": INTEGER,
"_id": STRING
}
}
[/code]

4. Edit details of existing book in the system : PUT /book/:isbn
Parameters: ISBN of the book and the updated book information in the below format in request body.

[code language=”javascript”]
{
"name":STRING,
"isbn":STRING,
"author":STRING,
"pages":INTEGER
}
[/code]

Response: The response is going to be the JSON object with the structure given below.

[code language=”javascript”]
{
"messaage": "Successfully updated the book",
"book": {
"__v": STRING,
"name": STRING,
"isbn": STRING,
"author": STRING,
"pages": INTEGER,
"_id": STRING
}
}
[/code]

5. Delete given book from the system : DELETE /book/:isbn
Parameter: ISBN of the book to be deleted
Response: The response is going to be the JSON object with the structure given below.

[code language=”javascript”]
{
"messaage": "Successfully deleted the book",
"book": {
"__v": STRING,
"name": STRING,
"isbn": STRING,
"author": STRING,
"pages": INTEGER,
"_id": STRING
}
}
[/code]

Implementing the RESTful API : ExpressJS + Body-parser + Node.js

As mentioned earlier I would be using express.js, node.js and body-parser.js node packages with MongooseJS. The below code sets up the packages and starts the web server on port 3300.

[code language=”javascript”]
//Express is required for creating Node.js based web apps
var express = require(‘express’);

//body-parser is used to parse the Request body and populate the req.
var bodyParser = require(‘body-parser’);

//mongoose is used for interacting with MongoDB
var mongoose = require(‘mongoose’);

var app = express();
app.set(‘port’, 3300);

//Configuring Express App to make use of BodyParser’s JSON parser to parse
//JSON request body
app.use(bodyParser.json());

var dbHost = ‘mongodb://localhost:27017/test’;
mongoose.connect(dbHost);
//Create a schema for Book
var bookSchema = mongoose.Schema({
name: String,
//Also creating index on field isbn
isbn: {type: String, index: true},
author: String,
pages: Number
});

//Create a Model by using the schema defined above
//Optionally one can provide the name of collection where the instances
//of this model get stored. In this case it is "mongoose_demo". Skipping
//this value defaults the name of the collection to plural of model name i.e books.
var Book = mongoose.model(‘Book’, bookSchema);

//Connecting to Mongod instance.
mongoose.connection;

//Starting up the server on the port: 3300
app.listen(app.get(‘port’), function(){
console.log(‘Server up: http://localhost:’ + app.get(‘port’));
});
[/code]

You can save the above code in file: express_demo.js and then run it using node express_demo.js , you should be able to see the below output:

[code]
Server up: http://localhost:3300
[/code]

Implementing GET /book

The below code implements this API:

[code language=”javascript”]
//Get all the books
app.get(‘/book’, function(req, res){
//Find all the books in the system.
Book.find({}, function(err, result){
if ( err ) throw err;
//Save the result into the response object.
res.json(result);
});
});
[/code]

In ExpressJS we create an application instance using express() (as seen above) and then setup the routes using the application instance. For example, for a GET call we use applicationInstance.get("ROUTE", handler(req, res){}), for a POST call we would set it up as applicationInstance.post("ROUTE", handler(req, res){}) and so on for other HTTP Methods like PUT, DELETE and others.

Implementing GET /book/:isbn

The below code is the implementation of the API

[code language=”javascript”]
//Get the details of the book with the given isbn
app.get(‘/book/:isbn’, function(req, res){
console.log("Fetching details for book with ISBN: " + req.params.isbn);
//The parameter in the route is accessed via request.params object.
Book.findOne({isbn: req.params.isbn}, function(err, result){
if ( err ) throw err;
res.json(result);
});
});
[/code]

In this Implementation the following are points of observation:

  1. Creating parameterized routes by using the :variable_Name in the route definition. In this case I have defined the route as /book/:isbn and this matches any url of form /book/abc123
  2. Accessing the path variable in the route via the request.params object. In this case I retrieve the ISBN string passed in the URL via req.params.isbn
  3. Using findOne with query object. In this case I am making use of MongoDB’s findOne() API along with the query object which is built using the ISBN information passed to retrieve one book information matching the ISBN

Implementing POST /book

This API is used to add a new book to the system. The information of the book is to be passed in the request body and we make use of the body-parser module to parse the json in the request body and populate it in the Node’s request object. The below code implements this API

[code language=”javascript”]
//Add a new book
app.post("/book", function(req, res){
console.log("Adding new Book: " + req.body.name);
var book = new Book({
name:req.body.name,
isbn: req.body.isbn,
author: req.body.author,
pages: req.body.pages
});

//Saving the model instance to the DB
book.save(function(err, result){
if ( err ) throw err;
//After successfully saving the book we generate a JSON response with the
//message and the inserted book information.
res.json({
messaage:"Successfully added book",
book:result
});
});
});
[/code]

In this implementation we read the JSON data passed by the Client, populate our instance of Book model class and persist the same to the DB using Mongoose API.

Implementation PUT /book/:isbn

This implementation is similar to GET /book/:isbn in terms of parameter handling and POST /book in terms of handling the book data passed from the client. We query for the existing information in the DB and then populate this existing data with the data passed from the client.

[code language=”javascript”]
//Update an existing book
app.put("/book/:isbn", function(req, res){
Book.findOne({isbn: req.params.isbn}, function(err, result){
if ( err ) throw err;

if(!result){
res.json({
message:"Book with ISBN: " + req.params.isbn+" not found.",
});
}

result.name = req.body.name;
result.isbn = req.body.isbn;
result.author = req.body.author;
result.pages = req.body.pages;

result.save(function(err, result){
if ( err ) throw err;
res.json({
message:"Successfully updated the book",
book: result
});
});

});
});
[/code]

Implementing DELETE /book/:isbn

Again this implementation is similar to GET /book/:isbn in terms of parameter handling and finding the book from the DB. To delete the book information we make use of findAndRemove API in Mongoose.

[code language=”javascript”]
//Delete an existing book
app.delete("/book/:isbn", function(req, res){
Book.findOneAndRemove({isbn: req.params.isbn}, function(err, result){
res.json({
message: "Successfully deleted the book",
book: result
});
});
});
[/code]

Testing the REST APIs

Now that I have shown you the implementation of individual APIs, lets go ahead and test the implemented APIs. For testing POST, PUT, DELETE I am making use of Postman Client’s plugin for Chrome.

GET /book

GET /book

GET /book/:isbn

GET /book/:isbn

POST /book

POST

PUT /book/:isbn

PUT

DELETE /book/:isbn

DELETE

Wrapping Up

I have shown you how the REST API is designed and then implemented using ExpressJS, Node.js and MongooseJS. For those looking for complete solution, copy the below code into a file named: express_demo.js

[code language=”javascript”]
//Saved in file: express_demo.js
//Express is required for creating Node.js based web apps
var express = require(‘express’);

//body-parser is used to parse the Request body and populate the req.
var bodyParser = require(‘body-parser’);

//mongoose is used for interacting with MongoDB
var mongoose = require(‘mongoose’);

var app = express();
app.set(‘port’, 3300);

//Configuring Express App to make use of BodyParser’s JSON parser to parse
//JSON request body
app.use(bodyParser.json());

var dbHost = ‘mongodb://localhost:27017/test’;
mongoose.connect(dbHost);
//Create a schema for Book
var bookSchema = mongoose.Schema({
name: String,
//Also creating index on field isbn
isbn: {type: String, index: true},
author: String,
pages: Number
});

//Create a Model by using the schema defined above
//Optionally one can provide the name of collection where the instances
//of this model get stored. In this case it is "mongoose_demo". Skipping
//this value defaults the name of the collection to plural of model name i.e books.
var Book = mongoose.model(‘Book’, bookSchema);

//Connecting to Mongod instance.
mongoose.connection;

//Starting up the server on the port: 3300
app.listen(app.get(‘port’), function(){
console.log(‘Server up: http://localhost:’ + app.get(‘port’));
});

//Get the details of the book with the given isbn
app.get(‘/book/:isbn’, function(req, res){
console.log("Fetching details for book with ISBN: " + req.params.isbn);

Book.findOne({isbn: req.params.isbn}, function(err, result){
if ( err ) throw err;
res.json(result);
});
});

//Get all the books
app.get(‘/book’, function(req, res){
//Find all the books in the system.
Book.find({}, function(err, result){
if ( err ) throw err;
//Save the result into the response object.
res.json(result);
});
});

//Add a new book
app.post("/book", function(req, res){
console.log("Adding new Book: " + req.body.name);
var book = new Book({
name:req.body.name,
isbn: req.body.isbn,
author: req.body.author,
pages: req.body.pages
});

//Saving the model instance to the DB
book.save(function(err, result){
if ( err ) throw err;
res.json({
messaage:"Successfully added book",
book:result
});
});
});

//Update an existing book
app.put("/book/:isbn", function(req, res){
Book.findOne({isbn: req.params.isbn}, function(err, result){
if ( err ) throw err;

if(!result){
res.json({
message:"Book with ISBN: " + req.params.isbn+" not found.",
});
}

result.name = req.body.name;
result.isbn = req.body.isbn;
result.author = req.body.author;
result.pages = req.body.pages;

result.save(function(err, result){
if ( err ) throw err;
res.json({
message:"Successfully updated the book",
book: result
});
});

});
});

//Delete an existing book
app.delete("/book/:isbn", function(req, res){
Book.findOneAndRemove({isbn: req.params.isbn}, function(err, result){
res.json({
message: "Successfully deleted the book",
book: result
});
});
});
[/code]

Before running this you would have to install the following packages: express, body-parser, mongoose using the command npm install.

Reference Books for Node.js

  • Professional Node.js: Building Javascript Based Scalable Software (English)
  • MongoDB : The Definitive Guide (English) 2nd Edition
  • MongoDB in Action (English)

Filed Under: ExpressJS, MongoDB, NodeJS Tagged With: NodeJS Tutorials

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved