2017-05-10 15 views
2

この簡単なコードをチュートリアルのサンプルログインHTMLフォームに載せて、ユーザーとパスワードがデータベースに登録されているかどうかを検出します。 このコードは、電子メールが存在する場合には検出できますが、パスワードは検出できません。
ここに何が間違っていますか?mysqlとhtmlを使用したnodejsログインフォーム

var express = require('express'); 
var app = express(); 
var server = require('http').createServer(app); 
bodyParser = require('body-parser'); 
var mysql = require('mysql'); 
var connection = mysql.createConnection({ 
     host: 'localhost', 
     database: 'chmult', 
     user: 'root', 
     password: '', 
    }); 
users = []; 
connections = []; 


app.get('/', function(req, res){ 
    res.sendFile(__dirname + '/'); 

}); 



app.use(bodyParser.urlencoded({ 
    extended: true 
})); 

/**bodyParser.json(options) 
* Parses the text as JSON and exposes the resulting object on req.body. 
*/ 
app.use(bodyParser.json()); 
connection.connect(); 


app.post('/', function(req, res){ 




var username= req.body.user.username; 
var password = req.body.user.password; 
connection.query('SELECT * FROM tesko WHERE username = ?',[username], function (error, results, fields) { 
if (error) { 
    // console.log("error ocurred",error); 
    res.send({ 
    "code":400, 
    "failed":"error ocurred" 
    }) 
}else{ 
    // console.log('The solution is: ', results); 
    if(results.length >0){ 
    if([0].password == password){ 
     res.send({ 
     "code":200, 
     "success":"login sucessfull" 
      }); 
    } 
    else{ 
     res.send({ 
     "code":204, 
     "success":"Email and password does not match" 
      }); 
    } 
    } 
    else{ 
    res.send({ 
     "code":204, 
     "success":"Email does not exits" 
     }); 
    } 
} 
}); 




}); 




app.listen(3231); 
console.log('Example app listening at port:3231'); 

私のHTMLフォーム

<form method="post" action=""> 
    <input type="text" name="user[username]"> 
    <input type="text" name="user[password]"> 

    <input type="submit" value="Submit"> 
</form> 
</html> 

私のテーブルの上に列名は(ユーザー名、パスワード)です。両方ともvarcharで、私はmd5を持っている他のテーブルで試しました。それでもパスワードを検出できません。

+2

Good!このエクササイズを放棄し、パスポートのようなものを使い始める。パスワードをクリアに保存することは非常に悪い考えです。 – e4c5

+0

パスポートの使用をお勧めします。ここにhttps://github.com/scotch-io/easy-node-authenticationにアクセスし、必要に応じて使用してください。それが役に立てば幸い!! –

+0

@ e4c5ありがとう私は次のステップでパスワードを暗号化します –

答えて

0

コードのこのビットは疑わしい:

私は未定義ことを期待したい
if(results.length >0){ 
    if([0].password == password){ 
    res.send({ 
    "code":200, 
    "success":"login sucessfull" 
     }); 
} 

特に[0].password

[0]は、配列へのインデックスではなく、ここでは配列リテラルです。前の行で判断して、結果[0] .passwordを代わりに使用することをお勧めします。

関連する問題