2017-05-14 52 views
0

我想做一個簡單的登錄使用nodejs和sequelize,我已經有一個用戶在數據庫上,我嘗試發送信息作爲req.body,並檢查它是否存在於哪裏clausuresequelize找到登錄retrives總是成功

像這樣:

router.post('/', function (req, res, next) { 
    console.log("hi"); 
    if (JSON.stringify(req.body) == "{}") { 
    return res.status(400).json({ Error: "Login request body is empty" }); 
    } 
    if (!req.body.username || !req.body.password) { 
    return res.status(400).json({ Error: "Missing fields for login" }); 
    } 
    User.find({ where: { username: req.body.username,password: req.body.password} }) 
    .then(function (user) { 
     return res.status(200).json({ message: "loged in!" }); 
    }).catch(function (err) { 
     return res.status(400).json({ Error: "There is no user with those fields" }); 
    }); 
}); 

它總是進入的消息中loged,就算我送不數據庫上存在的數據,任何信息爲什麼它是怎麼回事?

回答

1

您需要檢查是否user實際上定義:

User.find({ where: { username: req.body.username,password: req.body.password} }) 
    .then(function (user) { 
     if (! user) { 
     return res.status(400).json({ Error: "There is no user with those fields" }); 
     } else { 
     return res.status(200).json({ message: "loged in!" }); 
     } 
    }) 
    .catch(...) 

你假設一個查詢,不會產生任何結果將拋出一個錯誤,但它不會(因爲查詢運行成功)。

+0

你是絕對正確的:),我覺得別人是不是必要的,因爲你有return語句 –

0

此外,你可以使數據庫唯一索引完全確保用戶是唯一的。 順便說一下,這個索引將加速登錄過程。

Sequelize index docs ref