I have the following in the routing for my nodejs app, but it runs twice each time and tries sending both files. How do I stop it from running twice.
app.get('/', function(req, res){
data = validate(req.cookies.user,req.cookies.code,function(data) {
if (data == 'false'){
console.log('send to login');
res.sendFile(__dirname + '/views/login.html');
}
else {
console.log('send to chat');
res.sendFile(__dirname + '/views/chat.html');
}
console.log('USER DATA'+data);
});
});
First run works fine, and needs to stop there. But it auto runs a second time and undefined the results.
It calls the following function, which is a work in progress.
function validate (user, code, callback) {
con.query(
"SELECT * FROM tbl_users WHERE id = "+con.escape(user)+" and code = "+con.escape(code),
function(err,results) {
console.log('Validation Access');
console.log('User: '+user+' Code: '+code);
for (row in results) {
data = results[row];
console.log('Userdata: '+data);
if(data.id) {
console.log('Account Found');
callback(data);
}
}
console.log('Not Found');
callback('false');
}
);
}
The terminal output from the logging is
Express server listening on port 3000
Validation Access
User: 1 Code: 0
Userdata: [object Object]
Account Found
send to chat
USER DATA[object Object]
Not Found
send to login
USER DATAfalse
On looking at other posts there are no working answers
答案 0 :(得分:1)
问题是,即使找到了帐户,您的查询处理程序始终也会调用callback('false');
。解决该特定问题的最简单方法是在内部回调之后插入return
语句,如下所示:
for (row in results) {
data = results[row];
console.log('Userdata: '+data);
if(data.id) {
console.log('Account Found');
callback(data);
return; // prevent second callback
}
}
console.log('Not Found');
callback('false');