Saturday, May 30, 2020

Express.Js Middleware

Express.Js Middleware


Middleware


Middleware means something that is kept between two layers of the software. ExpressJS middlewares are functions that execute during the request-response lifecycle of the app and they can access the request object, the response object, and the next function. Express middleware functions can be applied to update request and response objects for jobs like parsing requests, adding response headers, etc. 

  • Middleware sits in the middle of the request and response cycle
  • Middleware has access to request and response object 
  • Middleware has access to the next function of the request-response life cycle


express middleware




Middleware functions can execute the following tasks:

  • Execute any code.
  • Update and modify the request and the response objects.
  • End the request-response cycle.
  • Invokes the next middleware in the stack.

var express = require('express');
var app = express();
//HTTP method for which the middleware function applies
app.use("/", function(req, res, next){
   console.log("A new request received");
   
   //Callback argument to the middleware function, called "next" by convention
   next();
});

app.listen(3000);

next()


A middleware can either terminate the HTTP request or forward it on to another middleware function using the next function otherwise the request will be left hanging. This “chaining” enables us to divide our code into pieces and create reusable middleware. It allows us to wait for the asynchronous database and network operations to complete before the next step.

The next() function is the third argument passed to the middleware function. It can be named anything, but by convention, it is good practice to name it as next().




next expressjs





Middleware types


Different kinds of middlewares are,

  • Middleware at Application-level, such as app.use 
  • Router level middleware, for example, router.use
  • Built-in middleware such as, express.static,express.json,express.urlencoded
  • Middleware for Error handling  app.use(err,req,res,next)
  • Third-party middlewares bodyparser,cookieparser

Writing a simple Express Middleware

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

// middleware
app.use(function(req, res, next){
    console.log(`Logged  ${req.url}  ${req.method} -- ${new Date()}`)
    next();
});


app.get('/test',function(req, res, next){
    res.send('<h1>Welcome</h1>');
});


app.post('/test',function(req, res, next){
    res.send('<h1>Welcome</h1>');
});

app.listen(3000,function(req, res){
    console.log('server running on port 3000');
});


Results,