Believed to have usedNode.jsYou must be familiar with middleware. The emergence of middleware, without exception, is born in order to improve our code writing efficiency, but many partners have used itExpressMiddleware, but did not begin to write their own middleware, today I will take you to write a simple middleware

1. Concept of middleware

1.1 Middleware refers to the processing part of a business process

2.2 Real life examples

In life, the sewage we use can only be discharged after treatment, and the intermediate processing steps are the meaning of the existence of middleware, and middleware is also like this, after filtering the required data to the user and the background.

2.ExpressCalling process

2.1 When the data of the client is transmitted to the Express server, it is preprocessed by one middleware after another and then responds to the client

3.nextThe role of

The next function is the key to implementing multiple middleware calls in succession, and represents the transfer of the flow relationship to the next middleware or route

4 Custom middleware (Define a middleware of your own)

1. Requirements: Simulate a middleware similar to Express.urlencoded, parse the data submitted by POST to the server

2. Implementation steps:

  • Defining middleware
  • Listening to thereqdataThe event
  • Listening to thereqendThe event
  • usequerystringThe module parses request body data
  • Mount the parsed data object asreq.body
  • Encapsulate custom middleware as modules

3. Define a middleware

App.use (function(req, RQS,next){//Copy the code
  1. Listening to thereqdataThe event

In middleware, you need to listen for the DATA event of the REQ object to get the data that the client sends to the server

If the amount of data is too large to be sent all at once, the client cuts the data and sends it to the server in batches. Therefore, a data event may be triggered multiple times. When a data event is triggered, the obtained data is only a part of the complete data, and the received data needs to be manually spliced

Req. on('data',(chunk)=>{STR +=chunk})Copy the code
  1. Listening to thereqendThe event

When the request body data is received, the end event of reQ is automatically triggered

We can get and process the complete request body data in the end event of req

Req.on ('end', ()=>{console.log(STR) //TODO: parse string format request body into object format})Copy the code
  1. Parse the request body data with the QueryString module

  2. Node.js has a queryString module built in to handle query strings. The module provides a parse() function that makes it easy to parse query strings into object formats

  3. The following code

Const qs = require(' queryString ') const body = qs.parse(STR) const body = qs.parse(STR)Copy the code

7. Mount the parsed data object as req.body

Upstream middleware and downstream middleware and routing share the same REQ and RES. Therefore, we can mount the parsed data as a custom attribute of REQ named REq.body for downstream use

Req.on ('end', () => {// console.log(STR) // TODO: Const body = qs.parse(STR) req.body = body next()}) const body = qs.parse(STR) req.body = body next()}Copy the code
  1. Encapsulate custom middleware as modules

To optimize the code structure, we can encapsulate our custom middleware functions into separate modules

9. Complete code

// Import express module const express = require('express') // create express server instance const app = express() // import node.js built-in Querystring module const qs = require(' queryString ') // Use ((req, res, next) => { Let STR = "// 2"; Req. on('data', (chunk) => {STR += chunk}) // 3. Req.on ('end', () => {// console.log(STR) // TODO: Request body data in string format, Const body = qs.parse(STR) req.body = body next()})}) app.post('/user', (req, Res) => {res.send(req.body)}) Listen (80, function () {console.log('Express server running at http://127.0.0.1')})Copy the code
Const app = express() // 1. Const customBodyParser = require('./14.custom-body-parser') // 2. Custom middleware functions, Use (customBodyParser) app.post('/user', (req, res) => {res.send(req.body)}) // Call the app.listen method, Listen (80, function () {console.log('Express server running at http://127.0.0.1')})Copy the code