【问题标题】:Call function with no argument and no default argument defined不带参数且未定义默认参数的调用函数
【发布时间】:2013-08-08 00:23:18
【问题描述】:

来自here的例子:

app.get('/account', ensureAuthenticated, function(req, res){
    res.render('account', { user: req.user });
});

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

我不明白ensureAuthenticated 的工作原理。它需要 3 个参数,没有设置默认参数。但是如果我不带参数调用它(在app.get 中),它确实执行正确,这怎么可能?

【问题讨论】:

    标签: javascript node.js authentication passport.js


    【解决方案1】:

    您实际上并没有在代码中的任何地方调用ensureAuthenticated;您正在传递对函数的引用,并且您的 http 框架稍后调用该函数(当向 /account 发出请求时)传递正确的参数。

    如果你写了ensureAuthenticated()(带括号),那么你会在没有参数的情况下调用它。如果没有括号,您将传递对函数的引用。

    【讨论】:

      【解决方案2】:

      Javascript 参数值始终是可选的。

      任何尚未传递的命名参数都只是undefined

      【讨论】:

      • ensureAuthenticated中,res.redirect被正确调用,这意味着res定义???
      • @PellaeonLin:这是由 Express 调用的,它确实传递了三个参数。
      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2021-04-08
      • 2012-06-14
      • 2020-11-16
      • 2016-12-12
      相关资源
      最近更新 更多