gpt4 book ai didi

mysql - NodeJS 和 MySQL,处理行

转载 作者:行者123 更新时间:2023-11-29 19:34:22 24 4
gpt4 key购买 nike

我是 NodeJS 初学者,目前正在使用 node、express 和 mysql 包。我正在尝试检查此人是否已经注册。

如果是这样,则应执行以下代码:

    req.session.user = user;
req.flash('success_notification', 'You are logged in');
console.log("creating session :" ,req.session.user);

但是,当我尝试检查它是否设置为 true 时,authenticated 始终保持“false”。

 if (authenticated === true)

有人知道我做错了什么吗?

这是我处理登录尝试的代码:

router.post('/login', function (req, res) {
var user = req.body.username;
var password = req.body.password;
var authenticated = false;

var query = "Select * from user where username = \'" + user + "\'" + " AND pw = \'" + password + "\'";

connection.query(query, function (err,rows,fields) {
if (err) console.log(err);
else if (rows.length) {
authenticated = true;
console.log(authenticated);
}
else {
console.log('False Password or Username');
}
});

console.log(authenticated);
if (authenticated === true) {
req.session.user = user;
req.flash('success_notification', 'You are logged in');
console.log("creating session :" ,req.session.user);
}

res.redirect('/');
});

最佳答案

这是一个回调问题。

我也遇到了同样的问题。

条件 if (authenticated === true) 在查询完成之前得到验证并返回,因此 authenticated 仅在查询完成后才变为 true它验证了自己。

让它适用于任何类型的 bool 查询返回的方法是将其包含在您的查询中以创建回调函数。

因此,如果您将条件封装在查询中,它应该可以正常工作。

router.post('/login', function (req, res) {
var user = req.body.username;
var password = req.body.password;
//var authenticated = false;

var query = "Select * from user where username = \'" + user + "\'" + " AND pw = \'" + password + "\'";

connection.query(query, function (err,rows,fields) {

var authenticated = false; //Encapsulate your authenticated variable since you won't need it outside this scope

if (err) console.log(err);
else if (rows.length) {
authenticated = true;
console.log(authenticated);
}
else {
console.log('False Password or Username');
}

/** Moved here */
console.log(authenticated);
if (authenticated === true) {
req.session.user = user;
req.flash('success_notification', 'You are logged in');
console.log("creating session :" ,req.session.user);
}

res.redirect('/');

});

// Moved wihin the your query
/*
console.log(authenticated);
if (authenticated === true) {
req.session.user = user;
req.flash('success_notification', 'You are logged in');
console.log("creating session :" ,req.session.user);
}

res.redirect('/');
*/

});

关于mysql - NodeJS 和 MySQL,处理行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41613643/

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