Middleware is a middle layer that is called between request and response. When the request is called middleware is called and it called before it sends response.

Topics Covered 

  • Calling middleware using app.use()
  • Calling for a specific route

Calling middleware using app.use()

Middleware is called before every request in the web page.

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

app.use(function (req, res, next) {
    console.log('Method is: ' + req.method + ' URL is: ' + req.url);
    next();
});

app.get('/', function (req, res) {
    res.send('Hello This is home page');
});

app.listen(3000, function () {
    console.log('App listening on port 3000!');
});

Calling for a specific route

Middleware is called before a /students route. In this way, we call middleware before any specific routes.

 

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

// Middleware get called before the original route and send the request
// This route is only called before /students route 
app.use('/students', function (req, res, next) {
    console.log('Method is: ' + req.method + ' URL is: ' + req.url);
    next();
});

// Before the route is called middleware get activated
app.get('/students', function (req, res) {
    res.send('Get all Student Data');
});

app.listen(3000, function () {
    console.log('App listening on port 3000!');
});

Conclusion:

Middleware is cleared to you. If you still have any doubt then do comment below.

Learn More: