javascript - Express Post函数中回调的执行顺序

标签 javascript node.js express callback

我在使用 [express 的路由处理方法] 时遇到了问题,特别是 Post 功能。
( http://expressjs.com/api.html#app.VERB )

我正在尝试解析 this passport example 中的一段代码

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
  res.redirect('/');
});

express 文件说

multiple callbacks are given, all are treated equally and behave just like middleware.

我的问题是,以下陈述是否准确:

middleware is like a bunch of tubes linked together. The middleware that comes first is the middleware that is listed first. If data is water, it will flow through the pipe that is listed first.

The same is true for the callbacks in route handing methods: the callbacks are pipes linked together, and if you pour data through these 'pipes', you are pouring it through the first callback listed and then the second callback in sequence. Is that true?

作为后续问题,这些回调应该返回什么?第一个回调是否返回响应,第二个回调接收并将其视为请求?什么应该从管道中出来,我可以将它插入第二个管道吗?

最佳答案

在这种情况下回调返回什么并不重要。他们正在调用 next 函数(此特定护照示例中未定义的第三个参数)。当调用 next 函数时,将使用与第一个相同的参数调用序列中的下一个中间件(相同的 req,相同的 res)

假设你有这段代码

function myFirstMiddleware(req, res, next) {//note the third parameter
    //you can change req and res objects
    next();
}

function secondMiddlewareInTheSequence(req, res, next) {
    //here you get the changes you've done to req and res since they are
    //the same objects
    res.end();
}

app.post('/', myFirstMiddleware, secondMiddlewareInTheSequence);

passport.authenticate 在内部所做的是,如果您的请求通过了正确的身份验证,则调用 next,因此您的中间件已通过控制。

您甚至可能不希望根据给定条件(几乎是护照的作用)将控制权传递给更多的中间件,就像这样。

function checkSecret(req, res, next) {
    if(req.query && req.query.secret === '42') {
        console.log('you are allowed to pass!');
        next();
    } else {
        console.log('you shall not pass!');
        res.status(403).end();
    }
}

如果将上述函数放在任何其他中间件之前,将阻止不包含 secret 的请求继续!

关于javascript - Express Post函数中回调的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162638/

相关文章:

javascript - IE点击事件跨度未触发

javascript - CSS 着色器适用于 2d Canvas 吗?

javascript - 如何以不区分大小写的方式删除字符串中的重复字母,以便该字母只出现一次?

node.js - 当package.json和yarn.lock不同步时,如何让yarn安装失败?

javascript - node.js 快速路由中 url 的正则表达式

javascript - 如果错误回调不执行以下代码

node.js - 在 Node/Express 的异步函数中捕获错误

javascript - 展开折叠树

javascript - node.js - 从模块捕获调试输出

node.js - 蒙戈没有数据