Express middleware in node (code demonstration and explanation)

1. The concept of middleware

  1. A simple understanding of the concept of middleware: the data is processed in steps from request to response, and then executed in an orderly manner. Each step is an intermediate processing link.

  2. The essence of middleware is a request processing method. We distribute the entire process from user request to response to multiple middleware for processing. The purpose of this is to improve the flexibility of the code and be dynamically scalable.

  3. The writing order of middleware is important

  4. The middleware itself is a method that accepts three parameters. When each request arrives at the server, nodejs creates a request object (request) for the request, which contains the data submitted by the client. At the same time, a response object (response) is also created, which is mainly responsible for responding to the server's data to the client. The last parameter next is a method, because multiple middleware can be used in an application, and if you want to run the next middleware, the previous middleware must run next().

    • request : request object
    • response : response object
    • next : the next middleware

next is a function used to call the next middleware, but not necessarily the next immediately next. Will find the first matching middleware backwards. If there is no match, continue to look back.
When a request enters a middleware, if next() is not called, the request will stay in the middleware.


2. In Express, there are several categories of middleware

2.1 Application-level middleware

Universal matching: Middleware that does not care about the request path and request method, which means that any request will enter this middleware

let express = require('express');

let app = express();

app.use(function (req,res,next) {
    
    
  console.log('1:收到请求');
  next();
})

app.use(function (req,res,next) {
    
    
  console.log('2:收到请求');
})

2.2 Routing middleware

2.2.1 concerned the request path /xxxmiddleware

// 路径以 /a 开头的请求才会进入
app.use('/a',function (req,res,next) {
    
    
  console.log('收到请求',req.url);
  res.send('end')
})

2.2.2 Middleware that strictly matches the request method and request path

//当一个请求是 get 请求,且请求路径以 /a 开头,就会进入该中间件
app.get('/a',function (req,res,next) {
    
    
  console.log('get /a');
})

//当一个请求是 post 请求,且请求路径以 /login 开头,就会进入该中间件
app.post('/login',function (req,res, next) {
    
    
  console.log('get /login');
})

2.3 Built-in middleware

Express has the following built-in middleware functions, screenshots of the official website
Insert picture description here

let express = require('express');
let path = require('path');

let app = express();

//开放资源目录
app.use('/public',express.static(path.join(__dirname,'./public/')));

2.4 Third-party middleware

To use third-party middleware to add functionality to Express applications, you need to install it first.

E.g,npm install cookie-parser

var express = require('express')
var app = express()
var cookieParser = require('cookie-parser')

app.use(cookieParser())

2.5 custom middleware

2.5.1 Error handling middleware

Configure a middleware that handles 404. If there is no middleware that can handle it , enter this middleware. The premise is to put this middleware at the end.

app.use(function (req, res, next) {
    
    
  res.send('404')
})

2.5.2 Global error handling middleware

let express = require('express');
let fs = require('fs')

let app = express();
app.get('/test', function (req, res, next) {
    
    
   //没有这个 cc.txt 文件,读取的时候会报错
  fs.readFile('./aa/bb/cc.txt', function (err, data) {
    
    
    if (err) {
    
    
      //当调用 next 的时候,如果传递了错误对象参数,则直接往后找到带有四个参数的应用程序级别的中间件
      next(err);
    }
  })
})

//注意四个参数一个都不能少!!!
//全局错误处理中间件,如果前边有一个中间件调用了next(err)方法,并传递了一个错误对象err作为参数,那么就会直接调用这个全局错误处理中间件
app.use(function (err, req, res, next) {
    
    
  res.status(500).json({
    
    
    err_code:500,
    message:err
  })
})

2.6 Notes

The same request object and response object are used by the middleware that passes through the same request.

That is to say, for the same request processed by different middleware, the req object is the same, and the res object is also the same

app.get('/a',function (req,res,next) {
    
    
  console.log('get /a');
  req.foo = 'hello';//在这里给req对象增加了一个属性 foo
  next();
})

app.get('/a',function (req,res,next) {
    
    
  console.log('get /a');
  console.log(req.foo);//由于是同一个请求,我们在这里就可以使用req对象的foo
})

3. Information

Express Chinese Net-Use Middleware

Express Chinese Net-Middleware List

https://blog.csdn.net/weixin_33881041/article/details/86128587

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/112496837