角度 - 平均堆栈 - 尝试在邮递员中检查用户密码,"bcrypt.compareSync"问题



因此,我试图在添加jwt令牌之前启用用户身份验证,但我遇到了一个问题,"if"检查引发了以下错误:

node_modulesbcryptjsdistbcrypt.js:265
throw Error("Illegal arguments: "+(typeof s)+', '+(typeof hash));
Error: Illegal arguments: undefined, string
at Object.bcrypt.compareSync

以下是我为引发问题的user.js编写的代码:

const { User } = require("../models/user");
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
router.get(`/`, async (req, res) => {
const userList = await User.find().select("-passwordHash");
if (!userList) {
res.status(500).json({ success: false });
}
res.send(userList);
});
router.get("/:id", async (req, res) => {
const user = await User.findById(req.params.id).select("-passwordHash");
if (!user) {
res
.status(500)
.json({ message: "The user with the given ID was not found." });
}
res.status(200).send(user);
});
router.post("/", async (req, res) => {
let user = new User({
name: req.body.name,
email: req.body.email,
color: req.body.color,
passwordHash: bcrypt.hashSync(req.body.passwordHash, 10),
phone: req.body.phone,
isAdmin: req.body.isAdmin,
apartment: req.body.apartment,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
});
user = await user.save();
if (!user) return res.status(400).send("the User cannot be created!");
res.send(user);
});
router.put("/:id", async (req, res) => {
const userExist = await User.findById(req.params.id);
let newPassword;
if (req.body.password) {
newPassword = bcrypt.hashSync(req.body.password, 10);
} else {
newPassword = userExist.passwordHash;
}
const user = await User.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
email: req.body.email,
color: req.body.color,
passwordHash: newPassword,
phone: req.body.phone,
isAdmin: req.body.isAdmin,
apartment: req.body.apartment,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
},
{ new: true }
);
if (!user) return res.status(400).send("the user cannot be created!");
res.send(user);
});
router.post("/login", async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res.status(400).send("The user is not found");
}
if (user && bcrypt.compareSync(req.body.password, user.passwordHash)) {
res.status(200).send("user Authenticated");
} else {
res.status(400).send("password is wrong");
}
});

module.exports = router;

所以这段代码尤其是的主要问题

if (user && bcrypt.compareSync(req.body.password, user.passwordHash))

如有任何帮助,我们将不胜感激。

消息错误表明req-body密码参数未定义

(req.body.password,user.passwordHash(=>已接收(未定义,字符串(

你必须这样做:

if (user && req.body.password && 
bcrypt.compareSync(req.body.password, user.passwordHash)) {
// send response
}

最新更新