var sender_username = req.session.user_id;
var recipient_username = req.body.recipient_username;
var content = req.body.content;
var sql = ' SELECT sender_username, recipient_username, COUNT(recipient_username) as count FROM message WHERE sender_username = "'+sender_username+'" AND recipient_username = "'+recipient_username+'" GROUP BY sender_username LIMIT 1 ';
var message_no = 0;
var data;
connection.query(sql, function(err, result) {
if (err) {
res.send(err);
}
else {
data = result;
// res.send(data); < - this works
// res.send(result); <- this works
// res.send(result.count); <- undefined
}
});
res.send(data); // undefined (can't seem to save to variable after connection.query())
res.send(result);
似乎有效。它给出了:
[{"sender_username":"sender","recipient_username":"recipient","count":2}]
我只是想获取count
的值并将其保存到变量中,但result.count
之类的东西由于某种原因返回undefined。
答案 0 :(得分:1)
因为JSON是一个数组,所以你应该像下面那样访问它
res.send(result[0].count);