这让我困惑了一段时间,真的不知道发生了什么。我使用node-mysql模块从MySQL获取数据,当结果准备就绪时,我将控制台记录它们并清楚地看到结果。
var sql = 'SELECT \
id, username, first_name, last_name \
FROM users\
WHERE username = ' + mysql.escape(req.params.username) + '';
pool.query(sql, function(err, result) {
if (err) throw err;
console.log(result[0]); //Object that contains all the fetched fields
if ((result[0].username).toLowerCase() == (req.params.username).toLowerCase()) {
console.log("We got a username!");
profile.userData = result[0];
profile.isAvailable = true;
profile.theme = getProfileSexTheme(profile.userData.sex);
} else {
console.log("We dont have a username");
}
renderPage(profile);
});
实际错误:
TypeError: Cannot read property 'username' of undefined
at Query.<anonymous> (/var/www/vhosts/MyWebApp/routes/profile.js:24:23)
at Query._callback (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/Pool.js:134:8)
at Query.Sequence.end (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Query._handleFinalResultPacket (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/protocol/sequences/Query.js:143:8)
at Query.EofPacket (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/protocol/sequences/Query.js:127:8)
at Protocol._parsePacket (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/protocol/Protocol.js:202:24)
at Parser.write (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (/var/www/vhosts/MyWebApp/node_modules/mysql/lib/Connection.js:72:28)
at Socket.EventEmitter.emit (events.js:95:17)
(profile.js:24就是这条线
if ((result[0].username).toLowerCase() == (req.params.username).toLowerCase()) {
)
从控制台日志中,我得到:
{ id: 24,
username: 'Anna304',
first_name: 'Anna',
last_name: 'Pell' }
We got a username!
(These gets don't come from the console log but from node)
GET /profile/Anna304 77ms
GET /profile/style.css 80ms
undefined
那是如何定义的?如果我评论console.log(result[0])
,它就不会出现,但是这个控制台日志实际上输出了包含查询结果的对象(就在我们可以看到的GET之前)。
我也尝试在加载页面后通过AJAX调用查询,并且它有效(但我想通过后端进行初始页面加载)。
有关如何进一步解决此问题的任何提示?