【问题标题】:in express how multiple callback works in app.get表达多个回调在 app.get 中的工作方式
【发布时间】:2014-04-12 16:49:21
【问题描述】:

我是节点的新手,所以如果我不明白,请原谅我。 在 node.js express 应用程序的 app.get 函数中,我们通常将路由和视图作为参数传递 例如

app.get('/users', user.list);

但在passport-google example 中我发现他们将其称为

app.get('/users', ensureAuthenticated, user.list);

其中 ensureAuthenticated 是一个函数

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/login')
}

简而言之,这意味着有多个回调在运行时被串联调用。我尝试添加更多功能以使其看起来像

app.get('/users', ensureAuthenticated, dummy1, dummy2, user.list);

我发现 ensureAuthenticated、dummy1、dummy2、user.list 被连续调用。

对于我的特定要求,我发现以上述形式顺序调用函数是非常优雅的解决方案,而不是使用异步系列。有人可以解释一下它是如何工作的,以及我如何实现类似的功能。

【问题讨论】:

标签: node.js express asynccallback


【解决方案1】:

在 Express 中,路径后面的每个参数都按顺序调用。通常,这是一种实现中间件的方式(如您在提供的示例中所见)。

app.get('/users', middleware1, middleware2, middleware3, processRequest);

function middleware1(req, res, next){
    // perform middleware function e.g. check if user is authenticated

    next();  // move on to the next middleware

    // or

    next(err);  // trigger error handler, usually to serve error page e.g. 403, 501 etc
}

【讨论】:

  • 有什么方法可以将一些数据传递给下一个回调,比如...比如sessionAccount
  • @Victor 是的,只需将数据附加到 req 对象 (req.sessionAccount = ...)。
  • @Jonas 非常感谢您!在你回答之前我自己试过了,我发现它有效
  • 如何在中间件函数中传递自定义参数?
  • @KetavChotaliya 这与 victor 提出的问题(并由 Jonas 回答)有何不同?
猜你喜欢
  • 1970-01-01
  • 2013-10-01
  • 2015-12-17
  • 2013-10-11
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多