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

前端 未结 9 1282
小蘑菇
小蘑菇 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:16

    Middlewares are functions executed in the middle after the input/source then produces an output which could be the final output or could be used by the next middleware until the cycle is complete.

    It is like a product that goes through an assembly line where it gets modified as it moves along until it gets completed, evaluated or gets rejected.

    A middleware expects some value to work on (i.e. parameter values) and based on some logic the middleware will call or not call the next middleware or send a response back to the client.

    If you can't still grasp the middleware concept, it is in a way similar to the Decorator or Chain of command patterns.

    0 讨论(0)
  • 2020-11-29 15:18

    After simplifying things, a web server can be seen as a function that takes in a request and outputs a response. So if you view a web server as a function, you could organize it into several pieces and separate them into smaller functions so that the composition of them will be the original function.

    Middlewares are the smaller functions that you can compose with others and the obvious benefit is that you can reuse them.

    0 讨论(0)
  • 2020-11-29 15:23

    In very basic term if i want to explain it like this i learn this from traversymedia youtube channel express crash course.
    ok so middle ware is a function who execute after you make a call to your route like this.

    var logger = function(req, res, next){
       console.log('logging...');
       next();
    }
    
    app.use(logger);
    

    This logger function execute every time you refresh your page that means you can write anything in it that you required to do after your page get rendered any operation api call, reset things basically anything. and put this middleware before your route function order of middleware is really important or it dons't work

    0 讨论(0)
提交回复
热议问题