Node.js在MySQL查询中崩溃

时间:2012-12-06 15:25:33

标签: mysql node.js express

我得到了这个问题的帮助。如果用户名或密码不在数据库中,我有登录脚本崩溃节点,这里是代码:

/* 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:无法读取未定义的属性“name”
      在Query.exports.login [as _callback](../ node-project01 / edit / login.js:18:19)
      在Query.Sequence.end(../node-project01/node_modules/mysql/lib/protocol/sequences/Sequence.js:66:24)
      在Query._handleFinalResultPacket(../node-project01/node_modules/mysql/lib/protocol/sequences/Query.js:138:8)
      在Query.EofPacket(../node-project01/node_modules/mysql/lib/protocol/sequences/Query.js:122:8)
      在Protocol._parsePacket(../node-project01/node_modules/mysql/lib/protocol/Protocol.js:165:24)
      在Parser.write(../ node-project01/node_modules/mysql/lib/protocol/Parser.js:60:12)
      在Protocol.write(../node-project01/node_modules/mysql/lib/protocol/Protocol.js:32:16)
      在Socket.ondata(stream.js:38:26)
      在Socket.EventEmitter.emit(events.js:96:17)
      在TCP.onread(net.js:396:14)

有关如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:1)

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

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

的问候,