Middleware

  1. The concept of middleware

    Middleware refers specifically to the intermediate processing links of business processes. The calling process of Express middleware is that when a request arrives at the Express server, multiple middleware can be called continuously, so as to perform Preprocessing.




  1. Format of Express Middleware

    The middleware of Express is essentially a function processing function (the formal parameters are different from ordinary functions, and there is more next). In the formal parameter list of the middleware function, must contain the next parameter. And the route handler only contains req and res.

    The next function is the key to realize multiple middleware continuous calls, it means that the flow relationship Pass to the next middleware or route. After the business processing of the current middleware is completed, must call the next function.

    1
    2
    3
    4
    5
    6
    7
    const express = require('express')
    const app = express()
    app.get('/', (req, res, next) => { //Middleware function
    next();
    })

    app.listen(80, () => {console.log('server running at http://127.0.0.1')})

    Define a simplest middleware function

    1
    2
    3
    4
    const mw = function(req, res, next){
    console.log('This is easist Middleware function');
    next();
    }


  1. Globally effective middleware

    any request initiated by the client, after reaching the server, will trigger the middleware, which is called the globally effective middleware. By calling app.use(middleware function), you can define a middleware that is globally effective:

    1
    2
    3
    4
    5
    6
    const mw = function(req, res, next){
    console.log('This is easist Middleware function');
    next();
    }

    app.use(mw) //Register as globally effective middleware

    Other routes can be written as usual. In this way, after the server receives the request, it will call the middleware function mw first, and then continue to match the calling route.


    A simplified form of the global middleware (replace the function with an anonymous function):

    1
    2
    3
    4
    app.use(function(req, res, next){
    console.log('This is easist Middleware function');
    next();
    })


  1. The role of middleware in development

    Between multiple middleware, share the same req and res. Based on this feature, we can uniformly add custom properties or methods to the req or res object in the middleware of upstream for the downstream of is used by middleware or routing.


    For example, add req.a = 10 on middleware 1 and res.c = 30 on middleware 2. In this way, in the final route, the property value can be obtained by accessing req.a and res.c.

    For example, we want to get the time when the server received the request. If you don’t use middleware, you need to write a time acquisition function in each route. If you use middleware, you only need to get the function at the time when the middleware is written, then assign the function value to req.time , and then the route can get the value from req.time .


  2. Define multiple global middleware

    Multiple global middleware can be defined consecutively using app.use(). After the client request arrives at the server, will call in the order defined by the middleware. E.g:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    app.use(function(req, res, next){ //The first global middleware
    console.log('call 1st global middleware');
    next();
    })
    app.use(function(req, res, next){ //The second global middleware
    console.log('call 2nd global middleware');
    next();
    })
    app.get('/user', (req, res) => { //Requesting this route will trigger the above two middleware in turn
    res.send('Home page.')
    })


  1. Locally effective middleware

    Do not use the middleware defined by app.use(), which is called a locally effective middleware, such as:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const mw1 = function(req, res, next){
    console.log("This is middleware 1")
    next()
    }
    app.get('/', mw1, function(req, res){ //mw1 middleware only takes effect in the current route. That is, the middleware that takes effect locally
    res.send('Home page.')
    })
    app.get('/user', function(req, res){ //mw1 middleware will not affect the following routes.
    res.send('User page.')
    })


  1. Define multiple local middleware

    These two methods are equivalent in the code.

    1
    2
    app.get('/', mw1, mw2, function(req, res){ res.send('Home page.') })
    app.get('/', [mw1, mw2], function(req, res){ res.send('Home page.') })


  1. Precautions
    1. Be sure to register middleware before routing. Because it is matched from top to bottom, the route will no longer match after the response.

    2. The request sent by the client can be processed by calling multiple middleware continuously.

    3. The next function must be called after the middleware is executed. If not called, the request cannot continue processing backwards.

    4. In order to prevent code logic confusion, do not write code after calling the next function.

    5. When multiple middlewares are called continuously, the req and res objects are shared among multiple middlewares.


Share