Reputation: 305
this function check_auth return always undefined ? cookie is ok result is ok, maybe the problem is the async call if yes how can fix it? I don't wont connection if the function is not satisfied
function check_auth(req,res){
var cookie=check_cookie(req);
var check_result_ret;
if(cookie){
console.log("exist cookie: "+cookie);
var sql = 'SELECT session_id,username,id FROM session WHERE session_id = ' + connection.escape(cookie);
connection.query(sql, function(err, results) {
if (err) throw err;
if (results.length > 0 && results[0]['session_id'] ==cookie) {
users[results[0]['session_id']]={username:results[0]["username"],id:results[0]["id"]};
check_result_ret=1;
}else{
check_result_ret=0;
}
});
}else{
check_result_ret=0;
}
return check_result_ret;
}
server node part
switch (path) {
case '/':
var test=check_auth(request,response);
console.log("result",test);
if(test==1){
fs.readFile("main.html", 'utf-8', function (error, data) {
//make somthing
});
}else{
send404(response);
}
break; etc....
Upvotes: 0
Views: 162
Reputation: 617
The problem is check_auth
returns check_result_ret
before the callback function(err, results)
of connection.query
is called .
I guess you need to read more on how asynchronous programming works .This might help http://www.sebastianseilund.com/nodejs-async-in-practice
maybe this helps,
check_auth(req,res){
...do stuff
connection.query(sql, function(err, results) {
if (err) throw err;
if (results.length > 0 && results[0]['session_id'] ==cookie) {
users[results[0]['session_id']]={username:results[0]["username"],id:results[0["id"]};
check_result_ret=1;
}
else{
check_result_ret=0;
}
var test = check_result_ret;
if(test==1){
fs.readFile("main.html", 'utf-8', function (error, data) {
//make somthing afer reading the file
anotherAsyncCall(input,options,function(output){
//do something with output
});
});
}
else{
send404(response);
}
})
Upvotes: 1