![](/img/trans.png)
[英]Error: Illegal arguments: undefined, string at Object.bcrypt.hashSync in MongoDB
[英]keeps getting "Illegal arguments: undefined, string at Object.bcrypt.hashSync"
我一直在我的 MERN 项目中使用 Bcrypt 我正在尝试创建一个身份验证系统我正在尝试在 Postman 上运行测试,但我不确定为什么我不断收到错误消息:“非法 arguments:未定义,字符串在 Object.bcrypt.hashSync"
这是 Controller 代码:
const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map((role) => role._id);
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
}
);
} else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
});
});
};
exports.signout = async (req, res) => {
try {
req.session = null;
return res.status(200).send({ message: "You've been signed out!" });
} catch (err) {
this.next(err);
}
};
错误消息: Illegal arguments: undefined, string at Object.bcrypt.hashSync
想说您将undefined
作为参数传递给hashSync
ZC1C425268E68385D14AB5074C17A4。 我们需要修复这个错误。
仔细查看发生错误的这一行:
password: bcrypt.hashSync(req.body.password, 8),
req.body.password
是undefined
,你可以通过console.log(req.body.password)
来验证。 问题是您将数据作为 URL 参数发送。 所以req.body
是一个空的 object 并且req.body.password
是undefined
。
In Postman, select the Body
tab, choose JSON format, then type your data as a JSON object. 然后,在您的代码中,使用express.json()
中间件以 JSON 格式解析请求。 您将拥有所需的 output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.