gpt4 book ai didi

mysql - Node.js 在 MySQL 查询上崩溃

转载 作者:行者123 更新时间:2023-11-29 14:09:29 25 4
gpt4 key购买 nike

我需要帮助解决我遇到的这个问题。如果用户名或密码不在数据库中,我的登录脚本会导致 Node 崩溃,代码如下:

/* Login */
exports.login = function(req, res){
var post = req.body;
var mysql = require('mysql');
var db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'node01',
});
var selectStmt = 'SELECT * FROM users WHERE name = "' + post.user +'"';
db.connect();

db.query(selectStmt, function(err, rows, fields) {
if(err) throw err;
else if(rows[0].name == post.user && rows[0].password == post.password){
req.session.auth_id = rows[0].id;
req.session.user = rows[0].name;
res.redirect('/adminindex');
}
else res.redirect('/admin');
});

db.end();
};

以及我得到的错误

TypeError: Cannot read property 'name' of undefined
at Query.exports.login [as _callback] (../node-project01/routes/login.js:18:19)
at Query.Sequence.end (../node-project01/node_modules/mysql/lib/protocol/sequences/Sequence.js:66:24)
at Query._handleFinalResultPacket (../node-project01/node_modules/mysql/lib/protocol/sequences/Query.js:138:8)
at Query.EofPacket (../node-project01/node_modules/mysql/lib/protocol/sequences/Query.js:122:8)
at Protocol._parsePacket (../node-project01/node_modules/mysql/lib/protocol/Protocol.js:165:24)
at Parser.write (../node-project01/node_modules/mysql/lib/protocol/Parser.js:60:12)
at Protocol.write (../node-project01/node_modules/mysql/lib/protocol/Protocol.js:32:16)
at Socket.ondata (stream.js:38:26)
at Socket.EventEmitter.emit (events.js:96:17)
at TCP.onread (net.js:396:14)

关于如何解决这个问题有什么想法吗?

最佳答案

嗯,考虑到你的问题是从12月开始的,我想你已经解决了这个问题。但是,您的问题可能是因为您的查询没有结果,然后“rows[0]”未定义。在使用“行”变量之前,您始终应该测试是否有任何结果,例如:

if (rows.length > 0) {
// your code here
}

问候,

关于mysql - Node.js 在 MySQL 查询上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13746868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com