gpt4 book ai didi

mysql - 无法使用express+mysql登录,注册有效

转载 作者:行者123 更新时间:2023-11-29 09:32:26 27 4
gpt4 key购买 nike

我尝试了各种方法让它工作,但我无法让登录页面工作,我认为问题出在快速方面。

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

最佳答案

密码或 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' });
});
});

编辑:用户密码位于 user[0].password 内,因此在 bcrypt.compareSync 中使用它解决了问题。

关于mysql - 无法使用express+mysql登录,注册有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420166/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com