gpt4 book ai didi

mysql - 错误: Failed to deserialize user out of session

转载 作者:行者123 更新时间:2023-11-29 18:03:28 24 4
gpt4 key购买 nike

我正在尝试将 Passportjs 与 Node.js 和 MySQL 一起使用。

我收到此错误:

Failed to deserialize user out of session

在注册代码中我有这个:

app.post("/register", function(req, res){
var hash = bcrypt.hashSync(req.body.password);
var q = "INSERT INTO users (username, email, hash) VALUES ('" + req.body.username +"','" + req.body.email +"','"+ hash +"')";
connection.query(q, function(err, result) {
if (err){
res.redirect("/register");
}else{
connection.query('SELECT * FROM users WHERE id = LAST_INSERT_ID()',
function(err, result){
var user = result[0];
req.login(user, function(err){
res.redirect('/');
});
});
}
});
});

在 LocalStrategy 中我有这个:

passport.use(new LocalStrategy(
function(username, password, done) {
var q = "SELECT username AS username, hash AS hash, id AS id FROM users WHERE username ='"+ [username] +"'";
connection.query(q, function(err, result) {
var hash = result[0].hash;
var isValid = bcrypt.compareSync(password, hash);
if (err) throw err;
if (isValid){
//redirect back to index
return done(null,{user:result[0]});
} else {
return done(null,false);
}
});
}
));

我相信这是我出错的地方,但我无法弄清楚,在序列化和反序列化中我有这个:

passport.serializeUser(function(user, done) {
done(null, user.id);
}); //store id in session

passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM users WHERE id ='"+id+"'",function(err,rows){
done(err, rows[0]);
});

});

最佳答案

经过两天的尝试修复后,我终于弄清楚了。在用户注册中,我应该将用户 ID 存储为这样的变量

   var user = result[0].id; 
req.login(user, function(err){
res.redirect('/');
});

以及用户登录的 localstrategy

var user = result[0].id;
return done(null,user);

我对此很陌生,我用谷歌搜索:了解 Passport 序列化反序列化。然后我发现this post这非常有帮助。
希望这对其他人有帮助。

关于mysql - 错误: Failed to deserialize user out of session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com