我试图在node-mysql查询回调中访问nodejs服务器会话变量,但我似乎无法访问或设置req.session中的任何变量。
connection.connect();
connection.query('SELECT id, firstname, lastname FROM users WHERE username = ? AND password = ?', [username, password] , function(err, rows, fields) {
if (err) throw err;
console.log(rows.length);
if(rows.length > 0){
console.log('Firstname: ' + rows[0]['firstname'] + ' Last Name: ' + rows[0]['lastname']);
req.session.firstname = rows[0]['firstname'];
req.session.lastname = rows[0]['lastname'];
} else {
console.log('No Results');
}
});
connection.end();
正如您在上面所看到的,我正在尝试将第一个名称和姓氏添加到会话中作为测试,以查看会话是否正常工作但最终将成为身份验证系统的一部分。
实现这一目标的最佳方法是什么。我错过了一些重要的中间件吗?
编辑:这是routes.login_process
中的完整代码var mysql = require('mysql');
var md5 = require('MD5');
exports.login_process = function(req, res){
var username = req.body.username;
var password = md5(req.body.password);
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
database : 'node',
password : 'test',
});
connection.connect();
connection.query('SELECT id, firstname, lastname FROM users WHERE username = ? AND password = ?', [username, password] , function(err, rows, fields) {
if (err) throw err;
console.log(rows.length);
if(rows.length > 0){
console.log('Firstname: ' + rows[0]['firstname'] + ' Last Name: ' + rows[0]['lastname']);
req.session.firstname = result[0]['firstname'];
req.session.lastname = result[0]['lastname'];
} else {
console.log('No Results');
}
});
connection.end();
res.writeHead(200);
res.end();
//res.redirect('http://www.bbc.co.uk');
}
这是从张贴到/ login
的表单发布的app.post('/login', routes.login_process);
答案 0 :(得分:1)
问题是查询是异步的,并且您的res.end()在启动连接后同步发生,从而在执行查询回调之前结束请求。响应结束后,无法再引用请求对象。将您的代码更改为:
connection.connect();
connection.query('SELECT id, firstname, lastname FROM users WHERE username = ? AND password = ?', [username, password] , function(err, rows, fields) {
if (err) throw err;
console.log(rows.length);
if(rows.length > 0){
console.log('Firstname: ' + rows[0]['firstname'] + ' Last Name: ' + rows[0]['lastname']);
req.session.firstname = result[0]['firstname'];
req.session.lastname = result[0]['lastname'];
} else {
console.log('No Results');
}
res.writeHead(200);
res.end();
});
connection.end();
这会导致您的响应等待查询完成。
请注意,我不确定connection.end()的确切位置。如果它在我放置的地方不起作用,请尝试将其移动到res.end()所在的位置(但是这可能会或可能不会起作用,具体取决于您使用的库是否在结束之前等待现有查询,或者只是将它们杀死)