What does middleware and app.use actually mean in Expressjs?

前端 未结 9 1328
小蘑菇
小蘑菇 2020-11-29 14:55

Almost every Express app I see has an app.use statement for middleware but I haven\'t found a clear, concise explanation of what middleware actually is and what

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 15:02

    Keep things simple, man!

    Note: the answer is related to the ExpressJS builtin middlware cases, however there are different definitions and use cases of middlewares.

    From my point of view, middleware acts as utility or helper functions but its activation and use is fully optional by using the app.use('path', /* define or use builtin middleware */) which don't wants from us to write some code for doing very common tasks which are needed for each HTTP request of our client like processing cookies, CSRF tokens and ..., which are very common in most applications so middleware can help us do these all for each HTTP request of our client in some stack, sequence or order of operations then provide the result of the process as a single unit of client request.

    Example:

    Accepting clients requests and providing back responses to them according to their requests is the nature of web server technology.

    Imagine if we are providing a response with just "Hello, world!" text for a GET HTTP request to our webserver's root URI is very simple scenario and don't needs anything else, but instead if we are checking the currently logged-in user and then responding with "Hello, Username!" needs something more than usual in this case we need a middleware to process all the client request metadata and provide us the identification info grabbed from the client request then according to that info we can uniquely identify our current user and it is possible to response to him/her with some related data.

    Hope it to help someone!

提交回复
热议问题