What is middleware
Middleware is a bunch of methods, which can receive the request from the client, respond to the request, or continue to hand over the request to the next middleware for further processing
Middleware consists of two parts: middleware method and request processing function
The middleware method is provided by Express, which is responsible for intercepting requests, and the request processing function is provided by the developer, which is responsible for processing requests
Routing is also middleware
app.get('Request path','Processing function') // Receive and process get requests app.post('Request path','Processing function') // Receive and process post requests
Routing Middleware
Multiple middleware can be set for the same request to process the same request multiple times (routing Middleware)
By default, the request matches the middleware from top to bottom. Once the matching is successful, the matching will be terminated (it will not be executed downward, and the subsequent routing processing will not be called, and the call to next() will continue to be executed downward)
const app = require('express')() // Middleware I app.get('/add',(req, res, next)=>{ req.name = "/add Routing Middleware" next() // Call the next Middleware }) // Middleware II app.get('/add',(req, res, next)=>{ req.age = 19 next() }) app.get('/add', (req, res)=>{ let {name, age} = req res.send({name, age}) }) // localhost:3000/add app.listen(3000,()=>console.log("The server started successfully"))
Global / application level middleware app use
app.use matches all request modes, and can be directly passed into the processing function to receive all requests
app.use((req, res, next)=>{ next() })
Path aware Middleware
Match / admin /admin/a /admin/a/b whose path starts with / admin
app.use('/admin',(req, res, next)=>{ next() })
Examples
const app = require('express')() // All requests are triggered app.use((req, res, next)=>{ req.name = "Application level Middleware" next() }) // /admin app.use('/admin',(req, res, next)=>{ req.name1 = "/admin Request for path" next() }) app.get('/admin/add', (req, res)=>{ let {name, name1} = req res.send({name, name1}) }) // localhost:3000/admin/add app.listen(3000,()=>console.log("The server started successfully"))
Error handling Middleware
In the process of program execution, some errors will inevitably occur, such as file reading failure and database connection failure
By default, only synchronization errors can be captured
Asynchronous error handling
const app = require('express')() // All requests are triggered app.use((req, res, next)=>{ req.name = "Application level Middleware" next({err:'ffff'}) // Asynchronous error handling of incoming error parameters // Or throw an error. By default, only synchronization errors can be caught // thorw new Error("program execution error") // thorw "program execution error" // Or code error }) app.get('/admin/add', (req, res)=>{ let {name, name1} = req res.send({name, name1}) }) // error handling app.use((err,req, res, next)=>{ console.error(err) // next() incoming content res.status(500).send("error handling") }) app.listen(3000,()=>console.log("The server started successfully"))
Built in middleware
// express.static // express.json // express.urlencoded // .... // Open static resource path Join (_dirname, ". / public /") will be transformed into an absolute path app.use("/public/",express.static(path.join(__dirname,"./public/"))) app.use("/node_modules/",express.static(path.join(__dirname,"./node_modules/")))
Third party Middleware
// border-parser // compression // .... let bodyParser = require("body-parser") // post parameter processing app.use(bodyParser.urlencoded({extended:false})) app.use(bodyParser.json())
Middleware application
- Routing protection: when the client accesses the page to be logged in, it can first use the middleware to judge the user's login status. If the user does not log in, it will intercept the request and respond directly, and prohibit the user from entering the page to be logged in.
- The website maintenance announcement defines the middleware to receive all requests at the top of the route to directly respond to the client. The website is under maintenance. (define an app.use direct response content at the top)
- Custom 404 page (define an app.use response 404 content at the end) 404 example