In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the meaning of nodej middleware, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
In nodejs, middleware mainly refers to the method of encapsulating the details of all Http requests, which is the processing method from the initiation of the Http request to the end of the response. The behavior of middleware is similar to the working principle of the filter in Java, which is to let the filter process before entering the specific business process.
The operating environment of this tutorial: windows7 system, nodejs 12.19.0, Dell G3 computer.
Middleware concept
In NodeJS, middleware mainly refers to the method that encapsulates the details of all Http requests. A Http request usually involves a lot of work, such as logging, ip filtering, query string, request body parsing, Cookie processing, permission verification, parameter verification, exception handling, etc., but for Web applications, they do not want to be exposed to so many details, so middleware is introduced to simplify and isolate the details between these infrastructure and business logic, so that developers can pay attention to business development. In order to achieve the purpose of improving development efficiency.
The behavior of middleware is similar to the working principle of the filter in Java, which is to let the filter process before entering the specific business process. Its working model is shown in the following figure.
Middleware working model
Core implementation of middleware mechanism
Middleware is the processing method from the initiation of the Http request to the end of the response, which usually requires the processing of the request and response, so a basic middleware takes the following form:
Const middleware = (req, res, next) = > {/ / TODO next ()}
The following is to understand how the middleware works through the implementation of two middleware mechanisms.
Mode one
Three simple middleware are defined as follows:
Const middleware1 = (req, res, next) = > {console.log ('middleware1 start') next ()} const middleware2 = (req, res, next) = > {console.log (' middleware2 start') next ()} const middleware3 = (req, res, next) = > {console.log ('middleware3 start') next ()} / / Middleware array const middlewares = [middleware1, middleware2, middleware3] function run (req Res) {const next = () = > {/ / get the first middleware in the middleware array const middleware = middlewares.shift () if (middleware) {middleware (req, res, next)}} next ()} run () / / simulate the initiation of a request
Execute the above code, and you can see the following results:
Middleware1 startmiddleware2 startmiddleware3 start
If there is an asynchronous operation in the middleware, the next () method needs to be called after the flow of the asynchronous operation ends, otherwise the middleware cannot be executed sequentially. Rewrite middleware2 middleware:
Const middleware2 = (req, res, next) = > {console.log ('middleware2 start') new Promise (resolve = > {setTimeout () = > resolve (), 1000)}) .then (() = > {next ()})}
The execution result is the same as before, but the middleware3 will be executed after the middleware2 async completes.
Middleware1 startmiddleware2 startmiddleware3 start
Some middleware need to be executed not only before business processing, but also after business processing, such as logging middleware for counting time. In the first case, other code from the current middleware cannot be executed as a callback when next () is an asynchronous operation. Therefore, the subsequent operation of the next () method can be encapsulated into a Promise object, and the callback after the end of the business process can be completed within the middleware in the form of next.then (). The method to overwrite run () is as follows:
Function run (req, res) {const next = () = > {const middleware = middlewares.shift () if (middleware) {/ / wraps middleware (req, res, next) as a Promise object return Promise.resolve (middleware (req, res, next)}} next ()}
The calling mode of middleware needs to be rewritten as follows:
Const middleware1 = (req, res, next) = > {console.log ('middleware1 start') / / all middleware should return a Promise object / / Promise.resolve () method to receive the Promise object returned by the middleware For lower-level middleware to asynchronously control return next (). Then (() = > {console.log ('middleware1 end')})} const middleware1 = (req, res, next) = > {console.log (' middleware1 start') / / all middleware should return a Promise object / / Promise.resolve () method to receive the Promise object returned by the middleware For lower-level middleware to asynchronously control return next (). Then ((res) = > {console.log ("1", res) return 'middleware1 end' })} const middleware2 = (req, res, next) = > {console.log ('middleware2 start') / / all middleware should return a Promise object / / Promise.resolve () method to receive the Promise object returned by the middleware For lower-level middleware asynchronous control / / console.log ("next ()", next ()) return next (). Then ((res) = > {console.log ("2", res) return 'middleware2 end'})} const middleware3 = (req, res, next) = > {console.log (' middleware3 start') return next (). Then ((res) = > {console.log ("3") Res) return 'middleware3 end'})} const middlewares = [middleware1, middleware2, middleware3] function run (req, res) {const next = () = > {const middleware = middlewares.shift () if (middleware) {/ / console.log ("next", next) / / wrap middleware (req, res, next) as Promise object return Promise.resolve (middleware (req, res) Next)} else {return Promise.resolve ("end") }} next ()} run () / / simulate the initiation of a request
Results:
Async await implementation
Const middleware1 = async (req, res, next) = > {console.log ('middleware1 start') let result = await next (); console.log ("1", result)} const middleware2 = async (req, res, next) = > {console.log (' middleware2 start') let result = await next (); console.log ("2", result) return 'middleware2 end' } const middleware3 = async (req, res, next) = > {console.log ('middleware3 start') let result = await next (); console.log ("3", result) return' middleware3 end' } const middlewares = [middleware1, middleware2, middleware3] function run (req, res) {const next = () = > {const middleware = middlewares.shift () if (middleware) {/ / console.log ("next", next) / / wrap middleware (req, res, next) as Promise object return Promise.resolve (middleware (req, res, next))} else {return Promise.resolve ("end") }} next ()} run () / / simulate the initiation of a request
The above describes the call flow of multiple asynchronous middleware in the middleware mechanism, and the implementation of the actual middleware mechanism also needs to consider exception handling, routing and so on.
In the express framework, the implementation of middleware is mode one, and the global middleware and the middleware defined according to the request path in the built-in routing middleware work together, but the code in the current middleware can not be invoked after the end of business processing. The middleware in the koa2 framework is implemented in mode 2, which encapsulates the return value of the next () method into a Promise, which is convenient for the asynchronous flow control of the subsequent middleware, and realizes the onion ring model proposed by the koa2 framework, that is, each layer of the middleware is equivalent to a sphere. When it runs through the whole model, each sphere will actually penetrate twice.
Onion Ring Model of koa2 Middleware
The middleware mechanism of the koa2 framework is implemented very succinctly and elegantly. Here's a look at the core code that combines multiple middleware in the framework.
Function compose (middleware) {if (! Array.isArray (middleware)) throw new TypeError ('Middleware stack must be an Array') For (const fn of middleware) {if (typeof fn! = = 'function') throw new TypeError (' Middleware must be composed of functions')} return function (context, next) {let index =-1 return dispatch (0) function dispatch (I) {/ / index accumulates after the next () method is called to prevent the next () method from calling if (I) repeatedly
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.