我正在尝试在 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);