使用 req.flash 登录时的错误处理

errors handling on login with req.flash

我有一个问题,我的页面上不仅出现了闪现消息,还出现了 json 而不是错误消息:

但是,如果我在浏览器中单击 "back",我会按预期看到页面,上面有闪现消息

我的请求码:

const handleLogin = async (req, res) => {
  const { errors, isValid } = validateLoginInput(req.body);
  if (!isValid) {
    return res.status(422).json(errors);
  }
  const { email, password } = req.body;
  const user = await User.findOne({email});
  if (!user) {
    errors.email = AUTH_ERROR;
    req.flash('loginMessage', AUTH_ERROR);
    return res.status(404).json(errors);
  }
  const isMatch = user.validatePassword(password, user.password);
  const { id, role } = user;
  if (isMatch) {
    const payload = {id, email, role};
    jwt.sign(
      payload,
      config.JWTAuthKey,
      {expiresIn: 3600},
      (err, token) => {
        res.cookie(tokenCookieName, token, { maxAge: 60 * 60 * 24 * 7 , httpOnly: false });
        res.redirect('/');
      }
    );
  } else {
    errors.password = AUTH_ERROR;
    req.flash('loginMessage', AUTH_ERROR);
    return res.status(403).json(errors);
  }
};

另外,我的passport配置(我用的是jwt策略)

const config = (passport) => {
  passport.use(
    new Strategy(opts, (jwt_payload, done) => {
      User.findById(jwt_payload.id)
        .then((user) => {
          if (user) {
            return done(null, user);
          }
          return done(null, false);
        })
      /*eslint no-console: ["error", { allow: ["warn", "error"] }] */
        .catch(err => console.error(err));
    }),
  );
};

如有任何想法,我们将不胜感激,提前致谢。

事实证明这很容易。无需发回状态,只需

return res.redirect('/')

会成功的。需要的地方可以重定向。