【问题标题】:Why does the following middleware syntax not work for Express?为什么以下中间件语法不适用于 Express?
【发布时间】:2012-05-15 13:53:34
【问题描述】:

我指的是下面的例子:

https://github.com/jaredhanson/passport-local/blob/master/examples/login/app.js

特别是以下代码:

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

发布的代码运行良好。但是,如果我尝试通过执行以下操作来重构它:

app.post('/login', 
  authenticate,
  function(req, res) {
    res.redirect('/');
  });

function authenticate() {
    return passport.authenticate('local', { failureRedirect:'/fail', failureFlash:true });
}

事情不再起作用了。我做错了什么?

【问题讨论】:

    标签: node.js express passport.js


    【解决方案1】:

    我认为您必须调用authenticate()(带括号)才能执行函数并返回中间件。例如:

    app.post('/login', 
      authenticate(),
      function(req, res) {
        res.redirect('/');
      });
    

    按照您当前的设置方式,身份验证安装为路由处理程序,因此 express 使用 req、res 参数(未使用或响应)调用它。

    【讨论】:

    • 谢谢贾里德。也许这不是问的正确地方,但是您原来的 passport.authenticate 功能怎么也没有使用 req/res?
    • 这是一个设置函数,它返回一个采用req、res、next 的函数(见bit.ly/KGpg3I 第66 行)设置包括策略和任何选项,返回函数使用.这个设置函数返回一个函数是 Express 和 Connect 中间件中的一种常见模式,并且可以在相对较少的代码行中实现一些强大的功能。
    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 2014-02-23
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多