我正在尝试使用post请求将用户保存到mongodb数据库,如下所示,但我收到错误bcrypt错误:需要数据和哈希参数。这是一个非常简单的代码设置但我无法弄清楚任何东西错了。 车型/ users.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');
// User schema
const UserSchema = mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
required: true
},
username:{
type: String,
required: true
},
password: {
type: String,
required: true
}
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function(id,callback){
User.findById(id,callback);
}
module.exports.getUserByUsername = function(username,callback){
const query = {username:username}
User.findOne(query,callback);
}
module.exports.addUser= function (newUser, callback) {
bcrypt.genSalt(10,(err,salt) => {
bcrypt.hash(newUser.password, salt , (err, hash) =>{
if(err) throw (err);
newUser.password=hash;
newUser.save(callback);
});
});
}
const jwt = require('jsonwebtoken');
User = require('../models/users')
// // Register
router.post('/register', (req, res, next) => {
var newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, User) => {
if(err){
// res.json({success: false, msg:'Failed to register user'});
} else {
// res.json({success: true, msg:'User registered'});
}
});
});
// Authenticate
router.post('/authenticate', (req, res, next) => {
res.send('AUTHENTICATE');
});
// Profile
router.get('/profile', (req, res, next) => {
res.send('PROFILE');
});
module.exports = router;
答案 0 :(得分:15)
The error comes from the bcrypt.hash
method.
In your case, you have the following piece of code :
bcrypt.hash(newUser.password, salt , (err, hash) => { ... }
I think that your problem comes from the newUser.password
that must be empty (null
or undefined
). The error says data and salt arguments required
. It looks like your salt is correctly generated and you didn't check if newUser.password === undefined
, so here's my bet : somehow newUser.password
is undefined.
Also, you can check if the genSalt
method works fine by adding if(err) throw (err);
after calling it as you did for the bcrypt.hash
method.
Hope it helps,
Best regards
答案 1 :(得分:0)
删除bcrypt.hash()中的箭头=>
。使用老式的方法定义function() {}
答案 2 :(得分:0)
每只猫鼬文档:https://mongoosejs.com/docs/faq.html
问:我在虚拟,中间件,getter / setter或方法中使用了箭头功能,而此值是错误的。A。箭头函数处理此关键字的方式与常规函数大不相同。猫鼬吸气器/设置器依赖于此,以使您能够访问要写入的文档,但是此功能不适用于箭头功能。除非不想访问吸气剂/设置器中的文档,否则不要将箭头功能用于猫鼬吸气剂/设置器。
答案 3 :(得分:0)
确保属性与提供的一样,在我的例子中,我发送了一个带有大写 Password
的 P
属性,然后用一个小 {{ 1}} 给 password
函数的信。