This is the 17th day of my participation in the August Text Challenge.More challenges in August
Express middleware
1. Understand Express middleware
Express is best known for its middleware. An Express application is made up of many middleware. Each route is a middleware; Express middleware is the same as AOP for faceted programming.
AOP is faceted programming: isolate them into methods that do not guide the business logic, and change these behaviors without affecting the code of the business logic; AOP can be used to isolate each part of the business logic, so as to reduce the degree of coupling between each part of the business logic, improve the reusability of the program, and improve the development efficiency and maintainability. That is, in the existing code program, adding or deleting one or more functions in the program life cycle or horizontal flow does not affect the implementation of other functions.
In Express, middleware is a function that accesses the request object, the response object, and calls the next(call the next middleware) method. The following tasks can be performed in middleware functions:
- Execute any code
- Modify the Request or Response response object
- The request response period ends
- Call the next middleware
app.use((req, res, next) = > {
req.foo = 'bar';
res.handle=() = >{... }; next(); })Copy the code
The order of the middleware is very important, and the request and response obtained by the middleware are the same. The value added to request or response by the previous middleware can be obtained by the next middleware, but if they are exchanged in order, undefined will be returned.
Second, Express middleware classification
- Application-level middleware
- Routing level middleware
- Error handling middleware
- Built-in middleware
- Third-party middleware
1. Application-level middleware
-
Middleware that does not qualify anything, any request will go through it
app.use(function (req, res, next) { console.log('Time'.Date.now()); next(); }) Copy the code
-
Restrict the request path, only the request path matches the rule can match this middleware;
app.get('/user/:id'.(req, res) = > { console.log('Request Type', req.method); // GET next(); }) Copy the code
-
Multiple handler functions, which can be configured in one middleware; In this case, the next function is to find the next function, and when the last handler function is found, the next middleware;
-
You can also define multiple middleware for the same path and use next() to jump to the next middleware, but you can’t send multiple responses to middleware that processes the same path;
app.get('/user/:id'.(req, res, next) = > { if (req.params.id === '0') next('route'); else next(); }, function (req, res, next) { res.send('normal'); }) app.get('/user/:id'.function (req, res, next) { res.send('special'); } Copy the code
Res. send(‘special’); res.send(‘special’); res.send(‘special’)
To skip the rest of the middleware functionality from the router middleware stack, call next(‘route’) to pass control to the next route; Note: Next (‘route’) only works with middleware functions loaded using app.method () or router.method () (not app.use);
- Middleware can also be declared reusable in arrays that can be placed in
app.METHOD()
In the second argument to
2. Router level middleware
Router-level middleware works in the same way as application-level middleware, except that it is bound to the instance Express.Router ()
var router = express.Router();
Copy the code
Load router level middleware using router.use() and router.method () functions; You can create a router.js in a folder to create a route:
-
Introduce module, create routing instance; A routing instance is equivalent to a relatively small Express instance;
const express = require('express'); const router = express.router(); Copy the code
-
Configure routes and export them
router.get('/foo'.(req, res) = > { res.send('get/foo')})module.exports = router; Copy the code
-
App. js file to import the router.js file, and then mount the route app.use(router). App. use(‘/aaa’, router) requires /aaa/foo to match the route configured on the router.
3. Error handling middleware
Error-handling middleware always takes four parameters, which must be provided to identify it as an error-handling middleware function. You must write these four parameters even if you don’t need one; The error-handling middleware should be mounted after all the middleware
app.use((err, req, res, next) = > {
console.log(err);
res.status(500).json({
error: err.message
})
})
Copy the code
Pass anything to the next() function, and Express treats the current request as an error and skips all remaining error-free routing and middleware functions; So make it catch(err) in app.method (); When an error occurs again, a call to Next (err) skips other middleware to error-handling routes;
4. Process 404 middleware
After all routes are configured. Requests come in and are matched from top to bottom, which the 404 middleware returns after all routes have not been matched, unlike the error-handling middleware;
app.use((req, res, next) = > {
res.status(404).send('404 Not Found');
})
Copy the code
5. Built-in middleware
express.json
: parsingContent-Type
forapplication/json
Format request bodyexpress.urlencoded()
: parsingContent-Type
forapplication/x-www-form-urlencoded
Format request bodyexpress.raw()
: parsingContent-Type
forapplication/octet-stream
Format request bodyexpress.text()
: parsingContent-Type
fortext.plain
Format request bodyexpress.static()
: Hosts static resource files
6. Third-party middleware
Use steps:
-
Download third-party middleware packages, such as NPM install Morgan;
-
Configure the middleware (see the documentation
const morgan = require('morgan'); app.use(morgan(':method :status :res[content-length] :response-time ms')); Copy the code
Reference documentation