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

前端 未结 9 1316
小蘑菇
小蘑菇 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 14:58

    =====Very very simple explanation=====

    Middlewares are often used in the context of Express.js framework and are a fundamental concept for node.js . In a nutshell, Its basically a function that has access to the request and response objects of your application. The way I'd like to think about it, is a series of 'checks/pre-screens' that the request goes through before the it is handled by the application. For e.g, Middlewares would be a good fit to determine if the request is authenticated before it proceeds to the application and return the login page if the request is not authenticated or for logging each request. A lot of third-party middlewares are available that enables a variety of functionality.

    Simple Middleware example:

    var app = express();
    app.use(function(req,res,next)){
        console.log("Request URL - "req.url);
        next();
    }
    

    The above code would be executed for each request that comes in and would log the request url, the next() method essentially allows the program to continue. If the next() function is not invoked, the program would not proceed further and would halt at the execution of the middleware.

    A couple of Middleware Gotchas:

    1. The order of middlewares in your application matters, as the request would go through each one in a sequential order.
    2. Forgetting to call the next() method in your middleware function can halt the processing of your request.
    3. Any change the req and res objects in the middleware function, would make the change available to other parts of the application that uses req and res

提交回复
热议问题