我正在尝试使用post请求将用户保存到mongodb数据库,如下所示,但我收到错误bcrypt错误:需要数据和哈希参数。这是代码的非常简单的设置,但我不知道它有什么问题。models / 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); }); }); }
路线/users.js
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;
服务器正在运行,但是在使用邮递员chrome后显示请求错误,并且服务器停止工作,如图中所示。
错误来自bcrypt.hash方法。就您而言,您具有以下代码段:
bcrypt.hash
bcrypt.hash(newUser.password, salt , (err, hash) => { ... }
我认为您的问题来自newUser.password必须为空的(null或undefined)。错误说data and salt arguments required。看来您的盐是正确生成的,并且您没有检查是否newUser.password === undefined,所以这是我的赌注:某种程度上newUser.password是不确定的。
newUser.password
null
undefined
data and salt arguments required
newUser.password === undefined
另外,您可以像调用方法一样在调用后genSalt添加该方法,以检查该方法是否工作正常。if(err) throw (err);``bcrypt.hash
genSalt
if(err) throw (err);``bcrypt.hash
希望对您有帮助, 最好的问候