护照验证卡住并且不返回任何值

afk*_*kqs 1 javascript node.js express express-validator

这个验证工作正常

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/home',
    failureRedirect: '/login',
    failureFlash: true
  })
);
Run Code Online (Sandbox Code Playgroud)

但我试图在使用快速验证器进行身份验证之前验证表单的字段。

我带着那个来的

app.post('/login', function(req, res){
  req.checkBody('email', 'Email is required').notEmpty();
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('password', 'Password is required').notEmpty();
  var validationErr = req.validationErrors();

  if (validationErr){
    res.render('login', {
      errors: validationErr,
      failureFlash: true
    });
  } else {
    // authenticate once fields have been validated
    passport.authenticate('local-login', {
        successRedirect: '/home',
        failureRedirect: '/login',
        failureFlash: true // allow flash messages
    })
  }
});
Run Code Online (Sandbox Code Playgroud)

使用第二个代码,当我提交表单时没有任何反应,并且客户端给出错误消息localhost一段时间后没有发送任何数据。第一部分工作正常,当我提交空表单并达到验证方法时,我可以看到所有错误。我怀疑这个问题可能部分回答我的问题或者有点相关,但我无法理解。

Passport.js文档提供了一个带有函数的示例,但仅当身份验证成功时才会调用该函数,因此之后。我想在身份验证之前执行字段验证。

如果您需要护照验证码,请告诉我。

Jim*_* B. 6

passport.authenticate是一个函数。在您的第一个(工作)代码中,您将其称为中间件,其中它传递(req,res,next)的对象作为参数。

使用第二个代码,您尝试直接调用它而不带参数,并且客户端超时,因为它没有得到响应。

如果我没有遗漏什么,您可以通过将 (req, res) 传递给它来完成这项工作,如下所示:

  if (validationErr){
      res.render('login', {
          errors: validationErr,
          failureFlash: true
      });
  } else {
      // authenticate once fields have been validated
      passport.authenticate('local-login', {
          successRedirect: '/home',
          failureRedirect: '/login',
          failureFlash: true // allow flash messages
      })(req, res, next);
  }
Run Code Online (Sandbox Code Playgroud)