Expressjs Middleware-1

·

2 min read

Intro:-

Middleware is function that is access request object(req) and response object(res), it execute between window period, when server receive request and send the response. If the current middleware function does not terminate request response cycle, it must pass control to the next() (next middleware function).

Middleware function perform following work:-
-code execution
-changes request object/response object according to app requirement
-completing the request/response cycle
-if not complete the request/response cycle then call next(),which is next middleware function

There are five types of middleware functions in express js
-Application level
-Router level
-Error level
-In-built
-Third party

Task:-

you will create express js app with application level middleware

Software Requirements:-

Ubuntu-16.04
nodejs v14.15.3
express v4.17.1
npm v6.14.9

Level:-

Beginner

Prerequisite:-

Knowledge of Typescript language and text editor

Step1:-

i) Install express js

$ mkdir expressapp
$ cd expressapp
$ npm init
$ npm install -express save
ii) Create server.js

const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
  res.send('Welcome expressapp ');
});

app.listen(9000);

Step2:-

Apply Application level Middleware

example 1:-middleware function with no mount path.

   var express = require('express')
var app = express()

app.use(function (req, res, next) { //app.use() is middleware function
  console.log('Datenow:', Date.now())//print on console
  next()
})

example2:-

app.use((req, res, next) => {//app.use() is middleware
  console.log(req);//print on console
  next();
});
app.get('/', (req, res, next) => {
  res.send('Welcome expressapp');//access on localhost:9000
})

example3:-

app.use(function(req, res, next){
   console.log("pre execution, print at console");
   next();
});

//Route handler
app.get('/', function(req, res, next){
   res.send("codeexecution");
   next();
});

app.use('/', function(req, res){
   console.log('post execution, print at console');
});

middleware1_1.png example4:-

app.use('/expressapp/:id', function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

// example shows a route and its handler function .   
//This app is example  with mounted path.

app.get('/expressapp/:id', function (req, res, next) {
  res.send('Expressapp')
})    
`

exappmountedpath.png

Conclusion:-

After performing above steps, you made nano app, which create basic express js app and add application middleware. By making these app, you know the basic of app middleware function.