express - 注销用户的问题。使用 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。
解决方案
这不应该在服务器上完成。只需删除/使客户端发送的 jwt 令牌无效即可。通常,令牌存储在 localStorage 和/或 cookie 中。只需删除该令牌并刷新页面,用户就会注销。
推荐阅读
- vim - 如何使 `syn-match` 规则仅在特定位置匹配?
- htmx - 使用 HTMX 处理错误
- javascript - Express 中的自定义错误库未显示在 Axios catch 块中
- kotlin - Kotlin - 在后台进程中监听键
- c# - 将存储库注入 ApplicationUser:IdentityUser 时出现问题
- scheduling - 在 IBM Cplex 中为一项任务配备多个资源
- java - 如何将 HBase 行转换为对象数组
- r - 如果间隙大于特定时间间隔或特定行数,则删除 NA
- php - 删除 JSON 中的最后一个逗号
- python - 无法查询“”:必须是 Django 3.2 中的“用户”实例