我有一个带有来自flexiage的mysql插件的node.js服务器: 这是我的代码:
connection.query('SELECT * FROM students WHERE email="'+req.body.username+'" AND password="'+req.body.password+'"',function(err,rows){
if(rows.length)
{
var response=new Object;
connection.query('SELECT * FROM forums WHERE id="'+rows[0].courseInterest+'"',function(err,course){
response.subscription=course;
response.username=rows[0].email;
response.password=rows[0].password;
response.loginFailed=false;
response.loginAccepted=true;
});
}
else
{
var response=new Object;
response.username="";
response.password="";
response.loginFailed=true;
response.loginAccepted=false;
}
console.log(response);
res.setHeader('Content-Type', 'application/json');
res.send(response);
});
在控制台中我只得到一个空白对象。它确实在if条件下,但无法在构造中附加prpoerties。我的猜测是变量范围,因为如果我在connection.query构造中执行console.log,它会根据需要返回结果。 请光明。
答案 0 :(得分:2)
不,没有范围问题,因为范围不是基于JavaScript的块,并且您的变量声明已被提升。
响应为空,因为query
函数是异步的,您在mysql应答之前记录并发送响应。
在回调中回答浏览器:
var response=new Object;
var sendResponse = function(){
console.log(response);
res.setHeader('Content-Type', 'application/json');
res.send(response);
}
connection.query('SELECT * FROM students WHERE email="'+req.body.username+'" AND password="'+req.body.password+'"',function(err,rows){
if (rows.length) {
response=new Object();
connection.query('SELECT * FROM forums WHERE id="'+rows[0].courseInterest+'"',function(err,course){
response.subscription=course;
response.username=rows[0].email;
response.password=rows[0].password;
response.loginFailed=false;
response.loginAccepted=true;
sendResponse();
})
} else {
response=new Object;
response.username="";
response.password="";
response.loginFailed=true;
response.loginAccepted=false;
sendResponse();
}
});