1. Middleware concept
The so-called middleware refers to the intermediate processing link of business process
2. Global validation Middleware
-
Any request initiated by the client will trigger the middleware when it reaches the server
-
A global middleware can be defined by calling app.use (middleware function)
// Import required modules const express = require('express') const app = express() // //Define a simple middleware function // const kw = (req,res,next)=> { // console.log('This is the simplest middleware '); // //Transfer the flow relationship to the next middleware or routing // next() // } // //Global validation Middleware // app.use(kw) // simplify // First Middleware app.use((req,res,next)=>{ console.log('This is the simplest middleware'); next() }) // Second Middleware app.use((req,res,next)=>{ console.log('This is the simplest middleware 3333'); next() }) app.get('/',(req,res)=>{ console.log('Called/This route'); res.send('fdff') }) app.listen(3000,()=>{ console.log('complete'); })
3. Role of Middleware
Multiple middleware share one req and res. based on this feature, we can uniformly add custom attribute methods for req and res objects in the upstream middleware for use by the downstream middleware or router
4. Partially effective Middleware
- Middleware that does not use app.use() definition is called local middleware
const express = require('express') const app = express() // middleware const mv1 = (req,res,next) => { console.log('This is the number of intermediate pieces'); next() } app.get('/',(req,res)=>{ res.send('ggjg') }) app.get('/user',mv1,(req,res)=>{ res.send('ffddf') }) app.listen(3000,()=>{ console.log('complete'); })
5. Precautions for Middleware
-
Be sure to register the middleware before routing
-
The request sent by the client can be processed by calling multiple middleware continuously
-
After executing the business code of the middleware, don't forget to call the next() function
-
To prevent code logic confusion, do not write additional code after calling the next() function
-
When multiple middleware are called continuously, req and res objects are shared among multiple middleware
6. Middleware classification
-
Application level Middleware
- Middleware bound to app instances through app.use(), app.get(), or app.post(), is called application level middleware
-
Routing level Middleware
- The middleware bound to the express.Router() instance is called the routing level middleware
-
Error level Middleware
- Note: the error level middleware must be registered after all routes
const express = require('express') const app = express() app.get('/',(req,res)=>{ throw new Error('An internal error occurred on the server') res.send('fsaf') }) // Error level middleware, placed at the end of all routes app.use((err,req,res,next)=>{ console.log('An error has occurred'+err.message); res.send(err.message) }) app.listen(3000,()=>{ console.log('complete'); })
-
Express built-in Middleware
- express.static is a built-in middleware for quickly hosting static resources, such as HTML files, pictures, CSS styles, etc. (no compatibility)
- express.json parses the request body data in JSON format (* * * compatible * *, only available in version 4.16.0 + `)
const express = require('express') const app = express() app.use(express.json()) app.post('/user',(req,res)=>{ // req.body receive client request body res.send(req.body) }) app.listen(3000,()=>{ console.log('complete'); })
- express.urlencoded parses the request body data in URL encoded format (* * * compatible * *, only available in version 4.16.0 + ` with the same usage as above
-
Third party Middleware
7. Custom Middleware
- Manually simulate a middleware like express.urlencoded
// Import express module const express = require('express') // Create a server instance of express const app = express() // 4. Import Node built-in module querystring const qs = require('querystring') // Middleware for parsing form data app.use((req,res,next)=>{ // Define the specific business logic of the middle price // 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',rem =>{ str+=rem }) // 3. Listen for the end event of req req.on('end',()=>{ // 5. Call the qs.parse() method to parse the query string into an object const arr = qs.parse(str) req.body=arr next() }) }) app.post('/user',(req,res)=>{ // 6. Mount the parsed data object as req.body attribute res.send(req.body) }) // Call the app.listen method, specify the port number and start the web server app.listen(3000,()=>{ console.log('complete'); })
-
Package on the above basis
The server
// Import express module const express = require('express') // Create a server instance of express const app = express() // 4. Import Node built-in module querystring // Import middleware module const arr = require('./Encapsulation Middleware') // Global Middleware app.use(arr) app.post('/user', (req, res) => { // 6. Mount the parsed data object as req.body attribute res.send(req.body) }) // Call the app.listen method, specify the port number and start the web server app.listen(3000, () => { console.log('complete'); })
middleware
const qs = require('querystring') // Middleware for parsing form data module.exports=((req, res, next) => { // Define the specific business logic of the middle price // 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', rem => { str += rem }) // 3. Listen for the end event of req req.on('end', () => { // 5. Call the qs.parse() method to parse the query string into an object const arr = qs.parse(str) req.body = arr next() }) })