Breaking News

Tutorial 2: Express Module – A middleware or something more

Tutorial 2: Express Module – 
A middleware or Something more

Tutorial 1: NodeJS: An Asynchronous World
Tutorial 2: Express: Middleware or more...
Tutorial 3: Understanding Routing in Express
Tutorial 4: Develop a Static File Server
Tutorial 5: Using HTTPS with Express
Tutorial 6: Develop a JSON API server
Tutorial 7: Use Templates and Views with Express
Tutorial 8: Integrating MongoDB
Tutorial 9: Testing Express Applications
Tutorial 10: Securing Express

Express node module is one of the popular application frameworks.  It is a flexible framework and allows you use it in many ways. It wraps around 'http' core module thus making it use easier. Practically developers use other frameworks or develop their own framework that works over express. Broadly speaking, Express module helps in following ways:

1. Provides a better routing mechanism
2. Middleware
3. Helps in dividing your application into sub-applications or different modules.

Installing Express in your project
Before we learn about router and middle-ware concept, let us learn about what's the most practical approach installing Express and managing your project. It is recommended to create a package.json file which lists the local dependencies of your project. Somewhat it is analogous to your C++ or java makefile. To create a default package.json file, type the following command in your bash/command shell.

$ npm init –yes

It creates a default package.json file in the directory somewhat similar to shown below. It lists the dependencies e.g. We installed colors node module of version 1.1.2 In addition, there are other fields like description, keywords, authors related to your project.

Tutorial 2: Express Module – A middleware or something more


To install Express we shall use the following command:



$ npm install --save express

Once installed you can check contents of node_modules folder containing express sub-folder.

Tutorial 2: Express Module – A middleware or something more


We can simply check if express module is working fine by creating a simple “Hello World” web application server. Run the following snippet (i.e. node ex7.js) and test its output in your browser.


var express = require('express');

var app = express();

app.get("/", function(req, resp){
 resp.send("Hello World");
});

app.listen(9000, function(){
 console.log("Express Web Server running on port 9000");
});


You can verify by opening the url( http://localhost:9000) in a browser. It should show something similar to the following figure:

Running a simple express web server


What is a router in Express Module?

As we start developing our web application, it starts growing and becomes large and complex. That's why we try to modularize our application and divide it into multiple independently working modules or sub-applications.

One of the easiest ways is routing method provided by expressJS. Routing is a way to map HTTP verb or URL requests to specific function handlers.  The following figure illustrates routing syntax:


Tutorial 2: Express Module – A middleware or something more
The instance of expressJS (here app.xxx) could be any HTTP verb i.e. GET (app.get) or POST (app.post) or PUT or any other HTTP verb. The first argument can be a URI or URL path which can be a hard-coded path or variable name or a regular expression. The second argument request handler function to called for the matching URI.

The following snippet (node ex8js) illustrates basic routing.

var express = require('express');

var app = express();

app.get("/", function(req, resp){
 resp.send("Welcome to main page via HTTP GET request");
});

app.post("/", function(req, resp){
 resp.send("Welcome to main page via POST request");
});

app.get("/about", function(req, resp){
 resp.send("Welcome to about page");
});

app.get("/user/:user_name", function(req, resp){
 resp.send("Welcome " + req.params.user_name +" to your profile page");
});

app.use(function(req, resp) {
 resp.statusCode = 404;
 resp.end("Sorry! we couldn't find what you are looking for!");
});


app.listen(9000, function(){
 console.log("Express Web Server running on port 9000");
});



You may test the various methods in a browser or using command line headless HTTP client like curl (as shown below)

Tutorial 2: Express Module – A middleware or something more

Thus we see routing helps in modularizing the application into various sub-modules.


What is Middleware then in ExpressJS?


Middleware generally refers to software applications or module which focus on specific function or job. In expressJS middleware can be simply a built-in function or a third party module or another web service.

Generally in a web application, when a web request comes, there is chain of handler functions are executed something very similar to the following sequence:

  1. Logs the request type (it is handled by logger module or middleware)
  2. Authenticates the requesting user i.e. whether the user has logged in, session is still valid (authentication middleware takes care of this)
  3. Process the request, retrieves the desired information from a database. (business middleware and database middleware participate here)
  4. Builds the visual output and sends a response (Viewing middleware handles it).

Tutorial 2: Express Module – A middleware or something more


The chain of middleware handlers can modify the requesting or response data and/or defers it to next handler. ExpressJS have app.use( ) and next( ) methods to implement and chain of middlewares.

Here is the nodeJS snippet (ex9.js), you may run and see the output.

var express = require('express');

var app = express();

app.use(function(req, resp, next){
 resp.write('Requesting Method is:' + req.method + '\n');
 next();
});

app.get("/", function(req, resp, next){
 resp.write("Welcome to main page via HTTP GET request\n");
 resp.end();
});

app.get("/about", function(req, resp, next){
 resp.write("Welcome to about page");
 next();
});

app.get("/user/:user_name", function(req, resp, next){
 resp.write("Welcome " + req.params.user_name +" to your profile page\n");
 next();
});

app.use(function(req, resp) {
 resp.end("End of Message\n");
});


app.listen(9000, function(){
 console.log("Express Web Server running on port 9000");
});




Try to comment out next() and see what happens.

Tutorial 2: Express Module – A middleware or something more


In the next tutorial, we'll revisit expressJS router and how to call third party middleware.

No comments