2012-12-06 75 views
0

我需要幫助解決這個問題。我已經登錄腳本,崩潰節點如果用戶名或密碼不數據庫,這裏的代碼:Node.js在MySQL查詢上崩潰

/* 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)

關於如何解決此問題的任何想法?

+0

不要把代碼和錯誤上一個單獨的網站 - 把它們放在你的問題! –

回答

2

那麼,考慮到你的問題是從十二月,我想你已經解決了這個問題。 但是,你的問題可能是因爲你的查詢沒有結果,那麼'rows [0]'是未定義的。使用「行」的變量,你總是應該測試是否有任何結果,像以前一樣:

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

問候,