当我尝试通过邮递员通过路由添加新用户时,使用的语法如下:
{
"name":"Test Name",
"email":"testmail@gmai.com",
"username":"test123",
"password":"3214"
}
控制台响应我一个错误:“非法参数:未定义,字符串” 邮递员说“无法得到任何回应”
我的代码示例(user.js):
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.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);
});
});
};
api.js:
router.post('/register', (req, res, next) => {
let 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'});
}
});
});
我想使用bcrypt,如何解决?
编辑:整个错误日志:
C:\Users\ajaks\Desktop\meanproject\server\models\user.js:38
if(err) throw err;
^
Error: Illegal arguments: undefined, string
at _async (C:\Users\ajaks\Desktop\meanproject\node_modules\bcryptjs\dist\bcrypt.js:214:46)
at Object.bcrypt.hash (C:\Users\ajaks\Desktop\meanproject\node_modules\bcryptjs\dist\bcrypt.js:220:13)
at bcrypt.genSalt (C:\Users\ajaks\Desktop\meanproject\server\models\user.js:37:16)
at Immediate._onImmediate (C:\Users\ajaks\Desktop\meanproject\node_modules\bcryptjs\dist\bcrypt.js:153:21)
at runCallback (timers.js:810:20)
at tryOnImmediate (timers.js:768:5)
at processImmediate [as _immediateCallback] (timers.js:745:5)
[nodemon] app crashed - waiting for file changes before starting...
答案 0 :(得分:0)
创建addUser
函数时出现问题。要在猫鼬模型内部创建自定义函数,需要使用statics
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
UserSchema.statics.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);
});
});
};
module.exports = mongoose.model('User', UserSchema);
现在它可以工作了。有关更多信息,如何在猫鼬模型内部创建自定义函数,请参考此 https://mongoosejs.com/docs/guide.html#statics
您还可以在module.exports
中了解nodejs
的工作方式
https://www.sitepoint.com/understanding-module-exports-exports-node-js/