变量没有被覆盖的NodeJS
问题描述:
router.post('/loginv', function (req,res) {
var id = req.body.id;
var pass = req.body.pass;
if(login.login(id,pass)=='validated'){
res.sendfile('views/welcome.html');
}else{
res.send('dont give up');
}
var result = login.login(id,pass);
console.log(result);
});
module.exports={
login : function(id,pass){
var q = "SELECT * FROM user where id = ? and pass = ?";
var ret = 'default';
DB.DB.query(q, [id,pass], function (error,result) {
if(error){
console.log('not found');
ret = 'unrecognized';
} else{
console.log('found');
ret = 'validated';
}
});
return ret;
}};
的console.log:变量没有被覆盖的NodeJS
GET /login 304 4.028 ms - -
default
POST /loginv 200 40.558 ms - 12
found
found
,你可以看到RET从下面的代码返回的值不被改变,虽然它遵循的程序功能正常.. 我是新来的节点js和js的东西,所以任何意见和建议一定会有所帮助thx :)
答
DB.query()
是异步的,所以login
函数在返回ret
之前不会等待代码的执行。您需要向登录方法添加回调(或使用承诺)。
一个工作代码:
module.exports = {
login : function(id,pass,cb){
var q = "SELECT * FROM user where id = ? and pass = ?";
DB.DB.query(q, [id,pass], function (error,result) {
if(error){
console.log('not found');
cb(error, 'unrecognized');
} else{
console.log('found');
cb(null, 'validated');
}
});
}
};
其他文件:
router.post('/loginv', function (req,res) {
var id = req.body.id;
var pass = req.body.pass;
login.login(id,pass, function(err, result) {
if (err) {
console.log(err);
res.send('dont give up');
return;
}
if (result === 'validated') {
res.sendfile('views/welcome.html');
}else{
console.log('Unknown error');
}
})
});
我建议你阅读的链接发布here和this question它可以为您提供有关回调和承诺的想法。
PS:我不知道你正在使用DB的库,但你MUST净化输入做查询之前,如果库不为你做
+0
它的作品!感谢您的帮助和链接真的有帮助..一直试图解决这个问题几个小时 – senaflix
'DB.query()'是异步,所以'login'函数在返回'ret'之前不会等待代码的执行。您需要为登录方法添加回调(或使用承诺) – rpadovani
换句话说,在完成查询之前,登录函数会返回。查询数据库是一种异步或非阻塞的I/O操作。 –