node.js - express中间件,他是如何知道哪个中间件先处理,哪个中间件后处理的?
PHPz
PHPz 2017-04-17 14:47:22
0
2
723

如题,express中间件,他是如何知道哪个中间件先处理,哪个中间件后处理的?这不用我们管吗?如果我们 有2个自定义中间件有顺序要求,那应该怎么定义呢?

PHPz
PHPz

学习是最好的投资!

reply all(2)
小葫芦

Suppose the path you request is `/user', and the following two routes match your request at the same time. Then

  1. Theoretically, the middleware in these two route matches will be executed

  2. Whether the subsequent middleware is executed depends on the previous middleware, whether it is called next()

app.get('/user', function(req, res, next){
    console.log('1');
    next();
});

app.get('/user', function(req, res, next){
    console.log('2');
    res.send('user');
});

Express internally maintains this order through an array called stack.

xx.stack.push(fn1);
xx.stack.push(fn2)
巴扎黑

Just write the middleware that is called first in front, it’s that straightforward.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template