Middleware :Backbone of Express.js Part 2

Hi codeteasers,

In previous post we had discussed about basic of middleware.In this post we will see some different aspects of middleware. Before starting new aspects of middleware  at first revised what we had learnt  previously.

    • What is middleware?
    • Basic examples of middleware containing single middleware and containing multiple middleware.
    • Functionality of Middleware.
    • Types of Middleware

Middleware in Express

In this post we will learn how and where we have to use different types of middleware.So, before starting new concepts about middleware at first I summarized previous concept about middleware.

  • Conceptually middleware is a way to encapsulate functionality that operates on an HTTP request to your application.
  • Middleware is simply a function that contains three parameters req,  res and next.

            var express=require('express');

            var app=express();

            app.use(function(req,res,next){
               console.log('hello middleware');
              });
           app.listen(3000);

Run application

Open command prompt and run command


node middleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got hello middlewaremessage on your console.

  • Middleware has access to request and response object.
  • Next method tells middleware to use next middleware , if inside a middleware you don’t call next() method then at that middleware our request terminates.

Now we come to point that inside this post we will learn about different types of middleware and how to use these middleware.

Conceptually middleware is classified into five categories.
  • Application-level middleware
  • Route-level middleware
  • Error handling middleware
  • Built-in middleware
  • Third-party middleware
Application-level middleware

A middleware that effects whole application is known as application level middleware.

Application-level middleware starts with app.use and app.method.

for further understanding of Applicaton-level middleware we go through an Example.


Var app=require(‘express’);

app.use(function(req,res,next){

console.log(‘Hello Application-level middleware’);
});
app.listen(3000);

Run application

Open command prompt and run command


node applicationmiddleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got Hello Application-level middlewaremessage on your console.

where app denotes objects for whole application

Route-level middleware

Rout-level middleware is same as Application-level middleware but basic difference is that it bound instance of express.Router() instead of express() .


       Var express=require(‘express’);

        var router= express.Router();

       router.use(function(req,res,next(){

       console.log('Router middleware Router Example first middleware');

       /* to call next middleware we use next method*/

      next();

      });
     app.listen(3000);

Run application

Open command prompt and run command


node routmiddleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got Router middleware Router Example first middlewaremessage on your console.

Error handling middleware

Error handler middleware is same as other middleware like Application-level middleware and

Route-level middleware functions but difference is that it contains four parameters instead of three parameters.


var express=require('express');

var app=express();

 app.use(function(err,req,res,next){

     console.error(err.stack)
     
     res.status(500).send('Something broke');


}); 

app.listen(3000);

Run application

Open command prompt and run command


node errormiddleWare.js
Built-in middleware

The middleware functions that previously included with Express but now seperate in express modules.

Express has following built-in middleware functions.

express.static
Syntax  : express.static(root,[options])
express.json 
synatx  : express.json([options])
express.urlncoded 
syntax : express.urlncoded()
Third-party middleware

Express apps uses third party modules for adding functionality of application.

Installing required node.js module for adding required functionality inside application.

Below example shows installing and loading the cookie-parsing middleware function cookie-parser.
Installing cookie-parser


npm install cookie-parser

Implementation


      var express = require('express');

      var app = express();

      var cookieParser = require('cookie-parser');

      // load the cookie-parsing middleware

      app.use(cookieParser())

You should also visit
Use Ejs with Express.js

Node.js Database Connectivity with Postgresql

PostgreSQL Operation with Node.js

Create Server in Node.js

Middleware :Backbone of Express.js Part 1

 

Now, you can deploy your Node.js app to App Engine standard environment

 

Today we will discuss most important topic for developing web application in Node.js using Express framework.Express is a minimal and flexible framework for web and mobile application.A Express application is essentially a series of Middleware function calls one after another.

Middleware is core concept behind Express.js.

Because Middleware is core concept behind experss.js in case request processing and routing so,with better understanding of Middleware can be able help us to construct maintainable application with less line of code.
Middleware in Express
When the Express.js is running,it is listening to request.Each request is processed according to a defined chain of Middleware and routes, starting from top to bottom.

Request,and Response objects can be accessed by Middleware.

Create Middleware

For creating middleware we have require three parameters first parameter is req i.e requesting object second parameter is res i.e. responding object and our third parameter is next is a function and used for continuing for next Middleware.We will explain i detail latter in upcoming examples.

Example :

Containing Single middleware

In case of single Middleware our application contains single Middleware as we know that Middleware contains three parameters as we discussed previously first parameter is req i.e requesting object second parameter is res i.e. responding object and our third parameter is next is a function and used for continuing for next Middleware because in this case our application contains only one Middleware so our third parameter is optional.


//Declaring express module
var express = require('express');
var app = express();
//Create Middleware
app.use('/',function(req,res){
 console.log("hello World");
})
app.listen(3000);

Run application

Open command prompt and run command


node middleWare.js

After that to see your result open your browser and copy link.


localhost:3000

After refreshing browser you got hello world message on your console.

Containing Multiple Middlewares

When our application contains multiple Middleware then in that case our flow will be from top to bottom and for performing such operation by our Middleware contains three parameters as in above example contain two parameters and in this case our third parameter is next.

Note: next is absolutely a function which is used to continue flow inside our application from top to bottom from one middleware to another.

middleWare.js


var express = require('express');
var app = express();
//Creating first middleware having 3 parameters
app.use('/',function(req,res,next){
 console.log("Start");
 next();
})
//Creating second middleware having 3 parameters
app.get('/',function(req,res,next){
 res.send('Hello middleware');
 next();
})
/*Creating third middleware having 2 parameters it is not mendatory that our
last middleare doesnot contain only two parameters it can also conation third paremeter
and it is good for your better paractice. 
*/
app.use('/',function(req,res){
 console.log("End");
})
//it is port number
app.listen(3000);

Open command prompt and run command


node middleWare.js

After that to see your result open your browser and copy link


localhost:3000

And you will obtain result as shown bellow
Middleware in Express

Functionality of Middlware

  1. It can be able to execute any code.
  2. It make changes to request and response process.
  3. It stops after ending request response cycle.
  4. It can call next Middleware function in the stack.

On the basis of Application in Express.js Middleware can be categorized in following types:

  • Application-level middleware
  • Route level middleware
  • Error handling middleware
  • Built-in middleware
  • Third-party middleware

Use Ejs with Express.js

Express is a minimal and flexible Node.js framework which commonly used for developing web and mobile applications.

How to use Express.js ?

Because Express.js is a framework of Node.js hence for using it we have to at first install it and for installing it we use this following command.


npm install express

After executing command our package has been installed. Now we can be able to develop our web application, During developing web application we have also used template Engines for fast development and for speedy execution.

Benefit of template Engines
  1. Enables to use static file in application.
  2. The template replaces variable in a template file with actual values.
  3. At the client-side, Template file transforms into HTML file.

here are various type of templates are available like

  1. Pug
  2. Mustache
  3. EJS

here During developing application we are using EJS Template now we are going to install template and after that proceeding further.

For installing EJS write following command.


npm install ejs

After executing this command we are ready to create .ejs files i.e template files

Now it’s time to develop an application without wasting our time hence before developing an application it is mandatory that you should understand standard folder structure of application and here I have designed a folder structure for application as shown below.

From the above image, you can be able to understand the folder structure of the application. But still, I like to explain some points.

  1. node_modules (folder): contains required packages like express,ejs
  2. server.js: creates a server
  3. rest folders are located inside views folder

So, at first, we create a server for that

 class=”entry-title”server.js



// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/views'));

// use res.render to load up an ejs view file

// index page 
app.get('/', function(req, res) {
    res.render('pages/index');
});

// about page 
app.get('/about', function(req, res) {
    res.render('pages/about');
});

app.listen(3000);
console.log('Ur server is started on 3000');

Now we create include inside views folder which contains 3 files header.ejs, footer.ejs, head.ejs. class=”entry-title”

#krdheeraj #freelearning #selflearning #puppeteer #javascript #node.js
Express is minimal and flexible Node.js framework which commonly used for developing web and Mobile application.

Use Ejs with Express.js

 class=”entry-title”header.ejs


<!-- views/include/header.ejs -->

<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">

<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
EJS Is Fun
</a>

<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</div>
</div>
</nav>

footer.ejs

#krdheeraj #freelearning #selflearning #puppeteer #javascript #node.js
Express is minimal and flexible Node.js framework which commonly used for developing web and Mobile application.

Use Ejs with Express.js


<!-- views/include/footer.ejs -->
<p class="text-center text-muted">© Copyright 2018 <a href="http://www.krdheeraj.info/">krdheeraj.info</a></p>

head.ejs class=”entry-title”

#krdheeraj #freelearning #selflearning #puppeteer #javascript #node.js
Express is minimal and flexible Node.js framework which commonly used for developing web and Mobile application.

Use Ejs with Express.js


<!-- views/include/head.ejs -->
<meta charset="UTF-8">
<title>Mean stack Developer</title>

<!-- CSS (load bootstrap from a css folder) -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body { padding-top:50px; }
</style>

Now it’s time design pages in this application I have add two pages index.ejs and about.ejs class=”entry-title”

index.ejs


<!-- views/pages/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../include/head %>
</head>
<body class="container">

<header>
<% include ../include/header %>
</header>

<main>

<div class="jumbotron">
<h1>This is great </h1>
<p>Welcome to templating using EJS</p>
</div>

</main>

<footer>

<% include ../include/footer %>

</footer>

</body>

</html>

 

about.ejs


<!-- views/pages/about.ejs -->

<!DOCTYPE html>
<html lang="en">
<head>
<% include ../include/head %>
</head>
<body class="container">

<header>
<% include ../include/header %>
</header>

<main>
<div class="row">
<div class="col-sm-8">
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</div>

<div class="col-sm-4">
<div class="well">
<h3>Great Example of /express.js using templating engine ejs!</h3>
</div>
</div>

</div>
</main>

<footer>
<% include ../partials/footer %>
</footer>

</body>
</html>

Hence, now our web application is ready open command prompt write command


node server.js

then message has been displayed on command prompt

Ur server is started on 3000

it means your server has been started,

Now copy the below link and paste inside browser


localhost:3000

 

Explore more about Express

RESTful API with Express
Middleware: Backbone of Express.js Part 1
Middleware: Backbone of Express.js Part 2

PostgreSQL Operation with Node.js

Previously we have discussed Node.js Database connectivity with PostgreSQL.Today I have a prepared a complete tutorial of Basic SQL Operations like Creation,Insertion and Selection.We have discussed these Operations in different three  cases.

Case 1: for creating a table
Case 2: for Inserting values
Case 3: for Selection Operation


const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
console.log("Press 1 for create new table");
console.log("Press 2 for insert Operation");
console.log("Press 3 for fetch Data from Database");
rl.question('Enter your choice? ', (choice) => {
    var inputChoice = parseInt(choice);
    var pg = require("pg");
    var connectStr = "pg://postgres:root_123@localhost:5432/NewDatabase";
    var client = new pg.Client(connectStr);
 
    client.connect();

    switch (inputChoice) {
        case 1:
            // Create table 
            var executeQuery = client.query("CREATE TABLE IF NOT EXISTS empDetail(firstname varchar(64), lastname varchar(64))");
            executeQuery.on("end", () => {
                client.end();
            });
              console.log("Your table has been created ...");
            break;
        case 2:
             // Insert details inside table 
            var executeQuery = client.query("Insert Into empDetail(firstname, lastname) values('Ronald', 'McDonal')");
            executeQuery.on("row", function(row, result) {
                result.addRow(row);
            });
            console.log("Your Insert Operation has been Completed");
            break;
        case 3:
            // Select details from table
            console.log("You wnat to retreive Data");
            var executeQuery = client.query("SELECT * From empDetail");
            executeQuery.on("end", function(result) {
                var empDetail = JSON.parse(JSON.stringify(result.rows, null, " "));
                console.log(empDetail.length);
                for (var i = 0; i < empDetail.length; i++) {
                    console.log("Details ::" + empDetail[i].firstname + " ********* " + empDetail[i].lastname);

                }
            });

            break;
        default:
            console.log("Wrong Choice ");
            break;
    }
    rl.close();
});

OutPut :





Node.js Database Connectivity with Postgresql

PostgreSQL is a Powerful,Open Source object-Relational(Relational Database with Object Oriented Feature) database System.PostgreSQL runs on all major operating systems like Linux,Unix,Windows etc.

During Connection with PostgreSQL at first we install pg Package and to install this package we use this command.


npm install pg

Note : If you have install Latest version of Node.js then there is no problem but if it is old version.then at first install npm package for this purpose use this command.


npm install

After installing this package we follow these five steps for database connection as discussed below :
During Database connction we have to follow these 5 steps

  1. Import Packages
  2. Open a Connection
  3. Execute Query
  4. Extract Data
  5. CleanUp the Environment

Import Packages


var pg = require("pg");

Open a Connection


var connectString = "pg://postgres:root_123@localhost:5432/NewDatabase";
/*
 pg              :< package >
        postgres        :< PostgreSQL UserName >
        root_123        :< PostgreSQL password >
        @localhost:5432 :< host Name >
        NewDatabase     :< database Name >
*/

var client = new pg.Client(connectString);

client.connect();

Execute Query


var executeQuery = client.query("SELECT * FROM public.attendanceremark;");

Extract Data


executeQuery .on("end", function (result) {

    console.log(JSON.stringify(result.rows, null, "    ")); //Gives OutPut in JSONString format

    var details=JSON.stringify(result.rows, null, "    "); 


    var emp=JSON.parse(details);                 //Parse JSONString to JSON Format

   for(var i=0;i<emp.length;i++){

    console.log(":::::::: "+emp[i].empname+ " ********** " +emp[i].remarkid);
   // empname and remarkid are attributes of attendanceremark table
  }

cleanUP Environment


  client.end();

});

Hence our complete code


var pg = require("pg");

var connectString = "pg://postgres:root_123@localhost:5432/NewDatabase";
/*
 pg              :< package >
        postgres        :< PostgreSQL UserName >
        root_123        :< PostgreSQL password >
        @localhost:5432 :< host Name >
        NewDatabase     :< database Name >
*/

var client = new pg.Client(connectString);

client.connect();

var executeQuery = client.query("SELECT * FROM public.attendanceremark;");

executeQuery .on("end", function (result) {

    console.log(JSON.stringify(result.rows, null, "    ")); //Gives OutPut in JSONString format

    var details=JSON.stringify(result.rows, null, "    "); 


    var emp=JSON.parse(details);                 //Parse JSONString to JSON Format

for(var i=0;i<emp.length;i++){

    console.log(":::::::: "+emp[i].empname+ " ********** " +emp[i].remarkid);
// empname and remarkid are attributes of attendanceremark table
 }

Create Server in Node.js

In other programming languages it is complex task to create a server. During this process we have to face a lot of phases like install different types of software like WAMP and XAMP for PHP and apache for JAVA, But in Node.js after installing LTS our problem is solved. We have to use http module and adding few lines of codes.

HTTP module :

HTTP is a stateless data transfer protocol built upon a request/response model:clients make requests to servers, which then return a response.

Some Point regarding HTTP Module:

  • It is a built-in module.
  • It is allows Node.js to transfer data over Hyper Text Transfer Protocol.
  • It contains createServer method used for creating server in node.js.
Create Server in Node.js

After using Module http and adding few lines of code Server is created.
 Example :

  
   var http =require('http');

   var http = require('http');

    var server=http.createServer(function(req,res){

       res.writeHead(200,{'content-Type':'text/plain'});

       res.end('Hello Server');


});

server.listen('8080');

To Obtain Output we have to open command prompt and write following command.


localhost:8080

Output :

A Node server is typically created using the method of the http module: createServer

Proxy Server

by using a proxy, that one server can forwards requests to the right recipient.

Question : How to create Proxy Server in Node.js?

In Node.js it is very easy to create Proxy Sever after adding few lines of Codes Our Proxy Sever has been created as shown below.


var http = require('http');

var server=new http.Server();

server.on("request",function(request,socket){

       http.request({

           host:'www.google.com',
           method:'GET',
           path:"/",
           port:80
       },function(response){

           response.pipe(socket);

       }).end();

});
server.listen(8080);

To Obtain Output we have to open command prompt and write following command.


localhost:8080

Output :