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 :

 

Your Classroom with G suite for Education

Make your school result online with resultcube.com


Dear students and Teachers,

Happy 69th Republic Day to all teachers and students Be the part of Digital India I Dheeraj Kumar your own Instructor help you to make your education online I am absolutely passionate about it Are you?

If you are then good if not then what are you waiting for it is good for both you either you are a teacher or student If you are a teacher then you are guiding your student not only in School time but after school also) and If you are a student then you are always be in contact with your teacher and clear more and more doubts from them.

In previous post I delivered an how to make paperless with Google Apps but google is doing more than these products for your schools. Do you know Google has developed a complete panel for handling your school and maintaining online relationship between students and teachers. For this purpose Google has developed an online Platform G suite for education which is managed by Google team which is generally known as Google team for education, Now we move for more Details.

What is G suite for Education?

G suite is an online Platform developed by Google team for Education and purpose of this team is make education for everyone from anywhere, anytime Work, share and learn together with Google online Apps and complete the dream of our those Ancestors who saw dream that “on education their should right of everyone”.

Why we go for G suite for Education?

Now It is age of competition and to come ahead in any field you have to speed up yourself because without speed you can be able to face completion with world and Internet is one of the way to boost your speed with help of Gooogle. Because internet is medium from which you can be able to learn from anywhere , anytime on the planet.
Google is great tech giant in the world of internet. Google plays vital role in each and field related to your life with help of Internet i.e. either your business or education.
So I am collecting a package for you both teacher and student that made your learning journey more funny and comfortable.
Establish teacher student relationship

G suite provides online platform to establish a student and teacher relationship .Student can be able to post his query from anywhere, anytime and teacher can be able to answer those questions from anywhere anytime on the planet.
Setup a online classroom

During first year of my college days I had an illusion that Is Internet only used for posting photos and waiting for likes and shares, or we can be able to do something more with help of Internet and I got answer of my question. When I familiar with G suite for Education. With help of G suite we can be able to setup our classroom on Internet. Teacher can be able to assign task to their student , close the task after a period. Student can be able to view task, complete assignment and after completing their assignment they can be able to submit their assignment. Complete process will be done online from anywhere or any time.
Maintain your class schedules

It is beneficial for all of us to create a schedule for our classroom and follow schedules and it became easier with Google calendar. With help of Google calendar you can create your class routine and share with your students.To know more about Why we for GSuite? Go to its official Page for this click here
Is it G suite services are free of Cost?

Absolutely free of cost .Google plan to keep the core offering of G Suite for Education free. This offering includes user accounts for future incoming students. As you may know, Google was founded by a research project at Stanford University, and this is just one way Google can give back to the educational community.
For more question and answers please visit G suite common question and answer page.
Whole process that makes your class room smart and represent yourself more attentive and effective will be done by G suite.
It is absolutely lucky chance for our new generation that they use Internet for learning purpose and as a teacher it is our responsibility we establish such type of environment for our student and motivate them for doing so.

If you want to setup G suite in your school and want to get benefit of Google tools then for any doubts ask questions inside comment box.

Paperless classroom with Google Apps

Make your school result online with resultcube.com


Now a days technology became important part of our life. Whenever we find ourselves surrounded with some problem then we move toward our smart phone for finding solutions. we google our query with a great hope that we will be able to find our solution.

Above scenario is enough to introduce importance of google in our daily life. As we know that Google is one of the great tech giant on the plaint.

Google team are doing absolutely great every day for solving a common man problem with different way ,then how Google find himself lagging behind with others in Education sector.

Well Google is also doing amazing job in education sector also and due to Google we can be able to think about paperless classroom can be possible with Google (Now other tech giants are also doing great in education sector).

Now I am introducing some apps developed by google which can make paperless class room.
Some of Google products are :

  • Google Derive
  • Google Docs, Sheets, Slides, Forms
  • Google Sites
  • Google Calendar
  • Google classroom
  • Blogger

These absolutely amazing products developed by google and if you are youth of new generation then it will help you to make paperless classroom and make yourself different from others.

By using these tools you didn’t help only (if you are a teacher ) your students but also you also helped yourself because such habit increase your productivity because now your job is being done by internet also in that case when you are sleeping.

These all products can be managed by your single gmail account and most of the products are absolutely free till a fixed limit.
e.g. Google provides every user 15 Gigabytes of space for Google Derive where user can store his photos, Google Docs, Google Slides and Sheets along with your messages and attachments of gmail account.

If you required more than 15 Gigabytes of space then don’t worry Goolge full fill your requirement on your tiny payment.
Now I am giving a short description of each and every product developed by Google (which I have mentioned earlier).

Google Derive :- It is amazing product developed by Google you will love it a lot when you know its amazing feature, You can store your important document online which can be access by me around the whole world for this you have required only my gmail account and password. You can also be able to share your files and folders if you are teacher then with other teacher or with your students and if you are a student then with your friend and with your teacher.

If you want to know how I use Google derive then I am a big fan of Goolge derive from my college days I like to access my data from anywhere either from college or from room and It is not possible that I am with my laptop so at that time Goolge Derive helps me a lot.
As I have mentioned earlier Goolge provide 15 GigaBytes free onwards you have to pay some money and here it described inside table.

Storage Price (US$)
15 GB Free
100 GB $1.99 per month ($19.99 per year with 16% discount)
1 TB $9.99 per month ($99.99 per year with 17% discount)
2 TB $19.99 per month
10 TB $99.99 per month
20 TB $199.99 per month
30 TB $299.99 per month

 

Google Docs, Sheets, Slides, Forms : – You can create online Documents, Sheets (for handling your important data and calculations, and Slides keeps these along with you and access or share with your friends from anywhere on the planet.
Google Sites :- Google developed a new product where you can be able create your own site with 15 days trial after that you have to pay some amount to continue your services.

Google Calendar: – Google Calendar is online platform where you can schedule your plan and after creating plan you can also track it online.

Google classroom :- Google classroom is amazing tool developed by Google. By the help of Google classroom teacher can be able to create online assignment and set a time

Blogger : – It is one of the product developed by Google which I like most because you can be able to share your thoughts ,lectures , tutorials, study material , or anything that you want to share publically if you are teacher to your student and if you are student then your teacher and your friends. You can also make money from Blogger below I will provide my blogger link for your reference synapseTechno.