The principle of express middleware (app.use())

1. What is middleware

Middleware is a request processing method, which distributes the user's entire process from request to response to multiple middleware for processing. The purpose of this is to improve the flexibility of the code and to be dynamically expandable. The simple understanding is: filter the received requests layer by layer.

2. Middleware in express

The process of request processing is: after the server receives the request, if the server writes multiple middleware, it will be matched in sequence until the middleware that meets the requirements is matched, and then processed. It should be noted that the middleware through the same request is the same request object and response object

Middleware classification:

  1. Application-level middleware

    • Full match (does not care about any request path and request method, when the user requests it, if it is distributed to the middleware, it will directly process the request operation)

      app.use(function (req,res,next) {
              
              
        console.log('全匹配');
        next();
      })
      

      When the request passes through this middleware, it does not care about the request path and method, and directly enters the middleware for processing. Among them nextis a method to call the next eligible middleware. If you do not write next, it will stay in the current middleware and will not match other middleware.

    • Matches where the path /xx/starts (fuzzy matching)

      app.use('/a',function (req,res,next) {
              
              
        console.log(3333);
      })
      

      Only /a/the path starting with can be matched and processed successfully, for example: /a/bit can be matched successfully, but it /ab/bcannot be matched successfully

  2. Routing level middleware (exact match)

    Must be consistent with the request path and request method to match successfully

    app.get('/a',(req,res) => {
          
          
      console.log(1111);
      res.send('index.html');
    })
    

Next use:

  • No parameters

Check out the following scenarios:

app.use(function (req,res,next) {
    
    
  console.log('全匹配');
  next();
})

app.use('/a',function (req,res,next) {
    
    
  console.log(3333);
  next();
})

app.get('/a',(req,res) => {
    
    
  console.log(1111);
  res.render('index.html');
})

app.get('/',(req,res) => {
    
    
  console.log('2222');
  res.render('index.html',{
    
    
    name: 'chen'
  })
})

app.get('/',(req,res) => {
    
    
  console.log('44444');
})

The browser enters the url 127.0.0.1:3000/and traverses each middleware in turn, and matches the first completely matched middleware. After printing out 全匹配, it is called next, and then continues to match the middleware that meets the requirements, and the second full-matching middleware is not met. to /a/the path beginning with the direct passing, the third match to continue, because it is an exact match, still no match, when faced with the last middleware, the match is successful, the output 2222can be seen that nextthe conditions have always been looking for The browser requests the object, that is, it needs to comply with 127.0.0.1:3000/this request.

Here is another scene:

app.get('/a',(req,res,next) => {
    
    
  console.log(1111);
  next();
})
app.get('/a',(req,res) => {
    
    
  res.send('ok');
})

When accessed /a, it matches the output of the first middleware 1111, encounters next, matches the second middleware, and returns to the client ok. It can be seen that the request for matching middleware is a process of matching one by one, instead of the latter covering the former one. process.

  • With parameters

    app.use(function (req,res,next) {
          
          
      console.log('全匹配');
      let err = '出错了';
      next(err);
    })
    
    app.use('/a',function (req,res,next) {
          
          
      console.log(3333);
      next();
    })
    
    # 带有四个参数,且这四个参数必须写全
    app.use(function (err,req,res,next) {
          
          
      console.log(err);// 出错了
    })
    

    When accessing the /apath, if the first middleware is matched, next is encountered, and it has parameters, it will not match other middlewares, and go directly to the middleware with four parameters to match, which can be used for Unified handling of error responses

The principle of using third-party plug-ins:

Because the middleware that the same request passes through are the same request object and response object , when a middleware adds other content to the request object, other middleware that is successfully matched can access this new content. E.g:

# 访问'/'
app.use(function (req,res,next) {
    
    
  console.log(111);
  req.body = {
    
    
    name: 'chen'
  }
  next()
})

app.use('/',function (req,res,next) {
    
    
  console.log(req.body.name);// chen
})

The above code shows that when the first middleware is matched, the body attribute is added to the request object, and then when the second matching middleware is called, the new attribute content can be accessed. The third-party plug-in is in this way, modifying the request object and returning the corresponding content. When accessing other middleware, you can access the new content of the third-party plug-in, such as: body-parserplug-in

# 假设已经下载好了body-parser插件
# 引入包
const bodyParser = require('body-parser');
# 将body-parser函数作为参数传递到app.use中
app.use(bodyParser.urlencoded({
    
    extended: false}));
app.use(bodyParser.json());

app.get('/',(req,res)=> {
    
    
    console.log(req.body);
})

When the bodyParser is passed into the middleware as a function, operations such as adding the body attribute to the request object will be performed at this time. After the addition is completed, it must be called nextand then continue to match the next middleware. At this time, it can be in the exact matching middleware. Use the body attribute.

From the above series of use process, it can be seen that the middleware writing order still affects the request response.

3. Summary

Middleware is used as a means of filtering requests. Among them, the middleware in express mainly relies on next to connect multiple middleware. At the same time, because the middleware through the same request is the same request object and response object , it makes more Communication can be carried out between two middleware.

Practical application:

  • Use middleware to configure plug-ins according to needs
  • Process the request after filtering the unified request
  • Unified processing operations can be performed for error responses

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/115072038