Type of middleware in Express js – Application-level

An Express application can use any of the below mentioned types of middleware:

  • Application-level middleware : app.use

  • Router-level middleware : router.use

  • Error handling middleware app.use(err,req,res,next)

  • Built-in middleware : express.static,express.json,express.urlencoded

  • Third-party middleware : bodyparser,cookieparser

You can execute application-level and router-level middleware functions with an optional path and you can execute series of middleware function together.

Application-level middleware

Create Application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions.

Below is the example for middleware without path. Always it will be executed before the app receives a request.


var app = express()

app.use(function (req, res, next) {
  console.log('Execute before the request')
  next()
})

Below example for middleware with path. The function will be executed for any type HTTP request with path “/about/a”.


app.use('/about/:a', function (req, res, next) {
  console.log('The Type of request is :', req.method)
  next()
})

Below example shows a route and its handler function, it handles GET request to the ‘/about/a’ path.


app.get('/about/:a', function (req, res, next) {
  res.send('About Page')
})

Here is an example of loading a series of middleware functions at a specific path


//1.Use the express module
var express = require('express');
//2.Create an object of the epxpress module
var app = express();

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

app.get('/default', function (req, res) {
    res.send('Single Callback Page!')
  })

var server = app.listen(3000, function() {
    console.log('Listenint Port : 3000 ');
});

Output


Listenint Port : 3000
Request URL: /
Request Type: GET

Leave a Reply

Your email address will not be published. Required fields are marked *