我尝试了各种方法使其正常运行,但无法使登录页面正常工作,我认为这是快递方面的问题。
//index.js
const findUserByEmail = (email, cb) => {
return mc.query('SELECT * FROM user_login WHERE email = ?',[email], (err, row) => {
cb(err, row)
});
}
router.post('/login', (req, res) => {
const email = req.body.email;
const password = req.body.password;
findUserByEmail(email, (err, user)=>{
if (err) return res.status(500).send({ "message": 'Server error!', "status": '500'});
if (!user) return res.status(404).send({ "message": 'User not found!', "status": '404'});
const result = bcrypt.compareSync(password, user.password);
if(!result) return res.status(401).send({ "message": 'Password not valid!', "status": '401'});
const expiresIn = 24 * 60 * 60;
const accessToken = jwt.sign({ id: user.id }, SECRET_KEY, {
expiresIn: expiresIn
});
res.status(200).send({ "user": user, "access_token": accessToken, "expires_in": expiresIn, "message": 'Success!', "status": '200'});
});
});
我已经注册了,但是当我尝试上述代码时,如果数据库中有该帐户,它将在express中抛出此错误:
C:\JSProjects\IonicProjectV2\express-auth-demo2\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: Illegal arguments: string, undefined
at Object.bcrypt.compareSync (C:\JSProjects\IonicProjectV2\express-auth-demo2\node_modules\bcryptjs\dist\bcrypt.js:265:19)
答案 0 :(得分:1)
密码或user.password均未定义,因此bcrypt对此有所抱怨。
请像这样添加console.logs,并查看哪个未定义。
router.post('/login', (req, res) => {
const email = req.body.email;
const password = req.body.password;
console.log(password);
findUserByEmail(email, (err, user) => {
if (err) return res.status(500).send({ "message": 'Server error!', "status": '500' });
if (!user) return res.status(404).send({ "message": 'User not found!', "status": '404' });
console.log(user);
const result = bcrypt.compareSync(password, user[0].password);
if (!result) return res.status(401).send({ "message": 'Password not valid!', "status": '401' });
const expiresIn = 24 * 60 * 60;
const accessToken = jwt.sign({ id: user.id }, SECRET_KEY, {
expiresIn: expiresIn
});
res.status(200).send({ "user": user, "access_token": accessToken, "expires_in": expiresIn, "message": 'Success!', "status": '200' });
});
});
编辑:用户密码位于用户[0] .password内,因此在bcrypt.compareSync中使用此密码即可解决问题。