In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article Xiaobian for you to introduce in detail "how to use Express middleware in Node", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to use Express middleware in Node" can help you solve your doubts.
What is Express middleware
Middleware specifically refers to the intermediate processing link of the business process.
2. The calling process of Express middleware
When a request arrives at the server of Express, multiple middleware can be called successively to preprocess the request.
3. Middleware format
It's essentially a function handler.
Note: the next parameter must be included in the formal parameter list of the middleware function. The route handling function contains only req and res.
/ / the next parameter must be passed in the last const mw = (req, res, next) = > {. / / next () must be the last call to next ()} IV. The function of the next () function
The next function is the key to realize the continuous call of multiple middleware, which indicates that the transfer relationship is transferred to the next middleware or route.
5. Middleware with global effect
Any request made by the client, after arriving at the server, will trigger the middleware, which is called globally effective middleware. You can define a middleware that takes effect globally by calling server.use (middleware function). The sample code is as follows:
Const mw = (req, res, next) = > {next ()} const mw1 = (req, res, next) = > {next ()} / / globally effective middleware. The calling order of the middleware is based on the incoming order. Server.use (mw,mw1) 6. Locally effective middleware
Local middleware only takes effect on a specified routing path
Const mw = (req,res, next) = > {next ()} const mw1 = (req,res, next) = > {next ()} / / locally effective middleware server.get ('/', mw, (req,res) = > {res.send ('path: /')}) / / define multiple locally effective middleware / / 1, directly comma-separated server.get ('/', mw,mw1, (req) Res) = > {res.send ('path: /')}) / / 2, or use an array containing server.get ('/', [mw,mw1], (req,res) = > {res.send ('path: /')}) 7. The role of middleware
Share the same req and res among multiple middleware. Based on this feature, we can uniformly add custom properties or methods for req or res objects in the upstream middleware for downstream middleware or routing.
Const mw = (req, res, next) = > {/ / add attribute req.startTime=new Date () next ()} VIII. Five points for attention of Express middleware
Be sure to register the middleware before routing
The request sent by the client can be processed by calling multiple middleware in succession.
After executing the business code of the middleware, don't forget to call the next () function
To prevent code logic confusion, do not write extra code after calling the next () function
When multiple middleware are called successively, req and res objects are shared among multiple middleware.
IX. Classification of Express middleware
Application-level middleware
Routing-level middleware
Error-level middleware
Express built-in middleware
Third-party middleware
Detailed introduction:
Application-level middleware
Bind to the middleware on the app instance through app.use () or app.get () or app.post (), which is called application-level middleware. The code example is as follows:
/ / globally effective middleware (application-level middleware) server.use (mw,mw1) / / locally effective middleware (application-level middleware) server.get ('/', mw,mw1, (req,res) = > {res.send (`time of request to enter the server: ${req.startTime} `)})
Routing-level middleware
The middleware bound to the express.Router () instance is called routing-level middleware. Its usage is no different from application-level middleware. However, the application-level middleware is bound to the app instance, and the routing-level middleware is bound to the router instance. The code example is as follows:
Const router = require ('. / router/router') / / routing-level middleware router.use ((req,res,next) = > {next ()})
Error-level middleware
The role of error-level middleware: designed to catch exception errors that occur throughout the project, thereby preventing the project from collapsing abnormally.
Format ∶ error level middleware function processing function, there must be four parameters, parameter order from front to back, respectively (err, req, res, next).
Note: error-level middleware must be registered after all routes!
/ / artificial error server.get ('/ err', (req, res) = > {throw new Error ('human error thrown!') Res.send ('err Page')}) / / Middleware server.use ((err, req, res, next) = > {console.log (' error occurred:'+ err.message); res.send ('Error:'+err.message) next ()})
Express built-in middleware
Since Express version 4.16.0, Express has built in three commonly used middleware, which has greatly improved the development efficiency and experience of Express projects:
/ / configure built-in middleware server.use (express.json ()) for parsing data in application/json format / / configure built-in middleware server.use (express.urlencoded ({extended: false})) for parsing data in application/x-www-form-urlencoded format / / Test built-in middleware server.post ('/ user', (req,res) = > {/ / on the server) for parsing json You can use the property req.body to accept the request data sent by the client / / by default, if you do not configure middleware to parse form data, req.body is equal to undefined console.log (req.body) by default. Res.send ('ok')}) / / Test the built-in middleware server.post for parsing urlencoded (' / book', (req,res) = > {console.log (req.body) res.send ('book ok')})
Express.static quickly hosts built-in middleware for static resources, such as HTML files, pictures, CSS styles, etc. (not compatible)
Express.json parses request body data in JSON format (compatible, only available in version 4.16.0 +)
Express.urlencoded parses request body data in URL-encoded format (compatible, only available in version 4.16.0 +)
Third-party middleware
Middleware, which is not officially built into Express, but developed by a third party, is called third-party middleware. In the project, you can download and configure third-party middleware as needed, so as to improve the development efficiency of the project. For example, in previous versions of express@4.16.0, body-parser, a third-party middleware, was often used to parse the request body data. The steps to use are as follows:
Note: Express's built-in express.urlencoded middleware is further packaged based on body-parser, a third-party middleware.
Run npm install body-parser installation middleware
Import middleware using require
Call server.use () to register and use middleware
After reading this, the article "how to use Express middleware in Node" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.