I used middleware functions for Express today. As for its concept and use techniques, we will not mention. I’m just interested in the internal structure of this middleware function. So today I will talk to you about the principle of this middleware function.

Use skills

There are two things to be aware of when using middleware functions: app.use() to add a middleware function, and the next() flag in the callback function, which simply represents the next middleware function to execute.

Thought analysis

After using it, we can roughly understand that there is something inside that holds middleware functions, and that this is an array. So let’s just do this in a nutshell.

In Express, middleware functions are executed through callback functions. In this case, we simply simulate a compose function to call all middleware functions.

The fnmiddle() execution calls compose’s return function, which handles all of the middleware array’s functions. Within this return function, we recursively implement the flow.

The general principle of such a middleware function comes out, the overall understanding is still relatively simple, but the coverage of middleware ideas in the Web is still very wide, you can list and write a general idea, welcome to discuss together.