In node, middleware is a functional encapsulation method, which mainly refers to the method of encapsulating all http request details; http requests usually contain a lot of content, so middleware can be used to simplify and Isolate these details between infrastructure and business logic.
The operating environment of this tutorial: windows10 system, nodejs version 12.19.0, Dell G3 computer.
Nodejs middleware is conceptually a functional encapsulation method, which mainly refers to the method of encapsulating all Http request details.
In nodeJS, middleware mainly refers to the method that encapsulates all Http request details. An Http request usually includes 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 detailed processes, so middleware is used to simplify and isolate the details between these infrastructure and business logic, allowing developers to The author pays more attention to business development. His working model is as follows:
#Core implementation of middleware mechanism
Middleware is initiated from Http request to response The processing method during the end process usually needs to process the request and response, so a basic middleware is in the following form:
const middleware = (req, res, next) => { // TODO next() } 模拟最基本的中间件 // 定义简单的三个中间件 const httpMeth1 = (req, res, next) => { console.log('我是请求1') next() } const httpMeth2 = (req, res, next) => { console.log('我是请求2') next() } const httpMeth3 = (req, res, next) => { console.log('我是请求3') next() } // 中间件数组 const allHttpMeth = [httpMeth1, httpMeth2, httpMeth3] function run (req, res) { const next = () => { // 获取中间件 const allHttpMethitem = allHttpMeth.shift() if (allHttpMethitem) { // 执行 allHttpMethitem(req, res, next) } } next() } run() // 模拟请求发起
If there is an asynchronous operation in the middleware, it needs to be processed after the asynchronous operation process ends. Call the next() method, otherwise the middleware cannot be executed in order
Recommended learning: "nodejs video tutorial"
The above is the detailed content of What is node's middleware?. For more information, please follow other related articles on the PHP Chinese website!