I believe that those who have used Node.js must be familiar with middleware. The emergence of middleware, without exception, was born to improve our code writing efficiency. However, many small partners have used Express middleware, but they have not written their own middleware. Today I will take you to write a simple middleware
1. Concept of Middleware
1.1 so called Middleware ), It refers to the processing link in the business process
2.2 real life examples
In life, the sewage we use can only be discharged after treatment, and the intermediate treatment step is the meaning of the middleware, and the middleware is the same. After filtering, the required data is transmitted to the user and the background
2.Express calling process
2.1 after the data of the client is transferred to the Express server, it will be preprocessed by one middleware after another and then respond to the client
3. Role of next
The next function is the key to realize the continuous call of multiple middleware. It means to transfer the flow relationship to the next middleware or route
4. Custom middleware (define your own Middleware)
1. Requirements: simulate a middleware similar to express.urlencoded to parse the data submitted by post to the server
2. Implementation steps:
- Define Middleware
- monitor req of data event
- monitor req of end event
- use querystring The module parses the request body data
- Mount the parsed data object as req.body
- Encapsulate custom middleware into modules
3. Define a middleware
app.use(function(req,rqs,next){ //Business logic of Middleware })
- monitor req of data event
In middleware, you need to listen req Object data Event to get the data sent by the client to the server
If the amount of data is large and cannot be sent at one time, the client will cut the data and send it to the server in batches data Events may be triggered multiple times, each time data In case of an event, the obtained data is only a part of the complete data, and the received data needs to be spliced manually
//Define variables to store the request data sent by the client let str='' //Data time of listening req object (request body data sent by the client) req.on('data',(chunk)=>{ str+=chunk })
- monitor req of end event
When the request body data is received, it will be triggered automatically req of end event
We can req of end Event, get and process the complete request body data
//Listen for the end event of the req object (triggered automatically after the request body is sent) req.on('end' , ()=>{ //Print complete request body data console.log(str) //TODO: parse the request body data in string format into object format })
-
use querystring The module parses the request body data
-
Node.js Built in one querystring Module, which is specially used to process query strings parse() Function, you can easily parse the query string into the format of an object
-
The code is as follows
//Import the built-in module of Node.js processing querystring const qs = require('querystring') //Call the qs.parse() method to parse the query string into an object const body = qs.parse(str)
7. Mount the parsed data object as req.body
The upstream middleware and downstream middleware and routing share the same copy req and res, so we can mount the parsed data as req A custom attribute named req.body for downstream use
req.on('end', () => { // The complete request body data is stored in str // console.log(str) // TODO: parse the request body data in string format into object format const body = qs.parse(str) req.body = body next() })
- Encapsulate custom middleware into modules
In order to optimize the structure of the code, we can encapsulate the custom middleware functions into independent modules
9. Complete code
// Import express module const express = require('express') // Create a server instance of express const app = express() // Import the built-in querystring module of Node.js const qs = require('querystring') // This is the middleware for parsing form data app.use((req, res, next) => { // Define the specific business logic of the middleware // 1. Define a str string to store the request body data sent by the client let str = '' // 2. Listen to the data event of req req.on('data', (chunk) => { str += chunk }) // 3. Listen for the end event of req req.on('end', () => { // The complete request body data is stored in str // console.log(str) // TODO: parse the request body data in string format into object format const body = qs.parse(str) req.body = body next() }) }) app.post('/user', (req, res) => { res.send(req.body) }) // Call the app.listen method, specify the port number and start the web server app.listen(80, function () { console.log('Express server running at http://127.0.0.1') })
// Import express module const express = require('express') // Create a server instance of express const app = express() // 1. Import the self encapsulated middleware module const customBodyParser = require('./14.custom-body-parser') // 2. Register the customized middleware functions as globally available middleware app.use(customBodyParser) app.post('/user', (req, res) => { res.send(req.body) }) // Call the app.listen method, specify the port number and start the web server app.listen(80, function () { console.log('Express server running at http://127.0.0.1') })