Passport.js - 自定义未经授权的消息

时间:2021-03-15 10:03:53

标签: javascript node.js express passport.js

您好, 当我到达登录部分时,我正在为我的网站构建后端,一切正常,直到我尝试输入虚假信息以检查会发生什么。因此,当我尝试将我重定向到另一个页面并显示“未经授权”时。所以我尝试修复它,这是我写的。

app.post("/login", function (req, res) {
  // Other code...
  req.login(user, function (err) {
    if (err) {
      res.render("login", {
        alert: [{ field: "none", msg: "Username/password is incorrect!" }],
      });
    } else {
      passport.authenticate("local")(req, res, function () {
        if (res.statusCode == 401) {
          res.render("login", {
            alert: [{ field: "none", msg: "Username/password is incorrect!" }],
          });
        } else {
          res.redirect("/");
        }
      });
    }
  });
});

如果有人能提供帮助,我将不胜感激! ?

1 个答案:

答案 0 :(得分:0)

我认为您需要先对用户进行身份验证,然后根据错误呈现页面,或者您可以将错误消息传递给 express 默认错误处理程序。

app.post('/login', (req, res, next) => {
  passport.authenticate('local',
  (err, user, info) => {
    if (err) {
      return next(err);  // default express error handler - unauthorized 
    }

    if (!user) {
      return res.redirect('/signup'); // you can redirect user to signup page if needed
    }

    req.logIn(user, function(err) {
      if (err) {
        return next(err);
      }
      return res.redirect('/dashboard');
    });

  })(req, res, next);
});