【发布时间】:2019-07-07 03:17:46
【问题描述】:
我正在为用户身份验证构建一个基于 Express 的 Node API。我正在使用 mongo 来存储数据。使用邮递员,我通过传入以下对象提交了 /post 请求
{
"username": "abc",
"password": "abc123",
"email": "abc@ghi.com"
}
在 req.body 下。
这是我的 /post 函数在代码中的样子:
//create one user
router.post('/createUser', async (req, res) => {
if (!req.body.email || !req.body.password || !req.body.username) {
return res.status(400).send({
message: "No username/password/email specified"
});
}
const newUser = new User({
email: req.body.email,
username: req.body.username,
password: req.body.password
});
await User.create(newUser, (err, data) => {
//res.send(data);
if(err) {
console.log(err);
res.status(500).send('Error creating user');
}
});
});
User.create() 方法在后台调用 .save() 方法。我有保存加密密码的先决条件。在运行帖子时,我收到一条错误消息,上面写着UnhandledPromiseRejectionWarning: Error: data and salt arguments required
我做了一些控制台日志记录并注意到这是因为 user.password 以未定义的形式出现。所以看起来我的请求没有从邮递员那里得到正确的处理。
编辑: 这是架构:
const userSchema = new mongoose.Schema({
id: {
type: Number
},
email: {
type: String,
unique: true,
required: true,
},
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
});
userSchema.pre('save', (next) => {
const user = this;
console.log(user.password);
bcrypt.hash(user.password, 10, (err, hash) => {
if (err) {
next(err);
} else {
user.password = hash;
next();
}
});
});
有人可以帮我理解什么问题吗?
【问题讨论】:
-
你能分享你的架构吗?
-
您能分享一下您的
create()方法和schema定义吗? -
你能展示你的预钩吗?
-
我已将架构定义添加到问题中
-
您能否重写您的问题,因为问题看起来与 POST 操作本身无关,而是与您在
.pre操作中调用代码的方式有关。
标签: javascript node.js mongodb express mongoose