I have this error when I try to test my API to change password. How can I fix this error?
Controller:
exports.changePassword = (req, res) => {
try {
const user = User.findByPk(req.params.user_id);
var body = req.body;
if (!user) {
return res.status(400).send("invalid value");
}
const salt = bcrypt.genSaltSync(10);
const newPassword = bcrypt.hashSync(body.newPassword, salt);
bcrypt.compare(
body.password,
user.password,
salt,
async function (err, isMatch) {
if (err) {
throw err;
}
if (!isMatch) throw new Error("Password not matched!");
user.set(
{ password: newPassword, updated_at: now() },
{
where: {
user_id: user.user_id,
},
}
);
await user.save();
}
);
res.status(200).send("Password Changed successfully!");
} catch (error) {
res.send("An error occured");
console.log(error);
}
};
Here is the error:
Error: Illegal callback: string
at Object.bcrypt.compare (C:\Users\admin\Desktop\Local Project\node_modules\bcryptjs\dist\bcrypt.js:303:23)
at exports.changePassword (C:\Users\admin\Desktop\Local Project\controllers\user.controller.js:146:12)
at Layer.handle [as handle_request] (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\index.js:284:15
at param (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\index.js:365:14)
at param (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\index.js:376:14)
at Function.process_params (C:\Users\admin\Desktop\Local Project\node_modules\express\lib\router\index.js:421:3)
I don't think compare
function needs salt. Just try to use it like this:
bcrypt.compare(body.password, user.password, (error, isMatch) => {
...
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.