首页 > 解决方案 > 注销用户的问题。使用 JWT 身份验证的 Express 服务器 API

问题描述

我正在尝试创建一个全栈 mern 应用程序。我使用 jwt 身份验证。我会将令牌保存在本地存储中,然后通过反应从那里删除令牌。

我尝试过 req.logout()、req.logOut() 和 req.session.destroy(),但它不起作用。谢谢!

const signIn = (req, res) => {
  const { email, password } = req.body;

  User.findOne({ email: email })
  .then((user) => {
    if (!user) {
      const error = new Error('A user with this email could not be found');
      error.statusCode = 401;
      throw error;
    }

    if(!user.authenticate(password)) {
      const error = new Error('A user with this email could not be found');
      error.statusCode = 401;
      throw error;
    }

    const token = jwt.sign({ 
        email: user.email,
        userId: user._id.toString()
      }
      , 'somesupersecret'
      , { expiresIn: '1h' });

      res.status(200).json(
        { 
          message: 'User successfully logged in!', 
          token,
          userId: user._id.toString()
        });
      })
      .catch(error => {
        if (!error.statusCode) {
          error.statusCode = 500;
          next(error);
      }

    })
}

const logOut = async(req, res) => {
  try{
    await req.logOut();
    res.status(200).json(
    { 
      message: 'User successfully logged out!',        
    });
  }
  catch(error) {
    console.log(error);
  }
}

module.exports = {
  signUp,
  signIn,
  logOut
}

我变成了 TypeError 之类的错误:req.logOut is not a function。

标签: expresslogout

解决方案


这不应该在服务器上完成。只需删除/使客户端发送的 jwt 令牌无效即可。通常,令牌存储在 localStorage 和/或 cookie 中。只需删除该令牌并刷新页面,用户就会注销。


推荐阅读