我正在学习node.js并遇到此问题,我进行了简单的登录以进行练习,当我尝试获取用户rol和rol的名称时,(在第二个查询中)我可以获取信息,但是看起来喜欢它仅在mysql查询范围内可用,我如何使其可用,以便我可以将所有这些信息发送回json响应?正确的做法是什么?
在这里我粘贴我的代码:
app.post('/auth', function(req, res) {
var username = req.body.username;
var password = req.body.password;
if (username && password) {
var encryptedPass = sha1(password);
dbConn.query('SELECT * FROM users WHERE username = ? AND password = ? and active="1"', [username, encryptedPass], function(error, results, fields) {
if (results.length > 0) {
var row = results[0];
name = row.name+" "+row.lastname;
id_user = row.id;
var id_rol;
var rol;
dbConn.query('SELECT id_rol, name FROM users_roles INNER JOIN roles ON users_roles.id_user = roles.id and id_user="?"', [id_user], function(error, resultsRol, fields) {
var rowRol = resultsRol[0];
id_rol = rowRol['id_rol'];
rol = rowRol['name'];
console.log(id_rol, rol); // here it shows the result in the console
});
console.log(id_rol, rol);// here it shows the variables as undefined in the console
req.session.loggedin = true;
req.session.username = username;
var token = jwt.sign({username:req.session.username},key);
res.status(200).json({
username:req.session.username,
loggedin:1,
token:token,
name: name
})
} else {
res.send('Incorrect Username and/or Password!');
//res.redirect('/views/login.html');
}
res.end();
});
} else {
res.send('Please enter Username and Password!');
res.end();
}
});
谢谢!