Web
Analytics
Express JS middleware with example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

What is express middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Major task of middleware

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.




Example

  1. First Create new node application and create package.json , index.js and install node modules express and body- praser by following commands.
    npm install express
    npm install body-parser

     

  2.  Write following code into index.js
    var express = require('express')
    var app = express()
    const bp= require('body-parser')
    
    app.use(bp.urlencoded({extended: false}));
    app.use(bp.json());
    
     var mfun = function(req, res, next)
     {
       console.log('middleware is called');
       console.log(req.body.name);
       console.log(req.body.fname);
       next();
     }
     app.use(mfun);
    app.get('/', function (req, res) {
      res.send('GET Request')
    })
    app.post('/', function (req, res) {
      res.send('POST Request')
    })
    app.listen(3000)

     

  3. Run the program and start postman to see results
    nodemon index.js

     

    Output

    express middlware output