Node.js后端POST请求报错:newContact.save不是函数及bcrypt参数异常
解决你的MEAN栈POST接口报错问题
嘿,我帮你梳理下问题根源,你遇到的TypeError: newContact.save is not a function和Illegal arguments: function, string报错,主要是两个关键错误导致的:
1. 路由调用addRegistry时参数传递错误
看你的route.js里的POST接口代码,你创建了newContact实例,但调用Contact.addRegistry时只传了回调函数,没把实例传进去:
// 错误写法:只传了回调,缺少newContact参数 Contact.addRegistry((err, contacts)=> { // ... });
而你的addRegistry方法定义时第一个参数需要接收mongoose模型实例,现在这个参数被回调函数占用了,导致方法里的newContact变成了一个函数,自然没有save方法。
2. addRegistry中bcrypt哈希的参数错误
在contact.js的addRegistry里,你把整个newContact对象传给了bcrypt.hash,但bcrypt.hash要求第一个参数是字符串类型的密码,不是对象,这就触发了非法参数的报错:
// 错误写法:传入了整个newContact对象 bcrypt.hash(newContact,salt, (err,hash) => { // ... });
修复方案
步骤1:修正路由里的addRegistry调用
在route.js的POST接口中,把新建的newContact实例作为第一个参数传给addRegistry:
router.post('/contact',(req, res, next)=>{ let newContact = new Contact({ first_name: req.body.first_name, last_name: req.body.last_name, email_id: req.body.email_id, password: req.body.password }); // 正确写法:传入newContact实例 + 回调函数 Contact.addRegistry(newContact, (err, contact)=> { if(err) { res.json({msg:'Failed to add register', error: err.message}); } else{ res.json({msg:'Registry added successfully', contact: contact}); } }); });
步骤2:修正addRegistry的bcrypt哈希逻辑
在contact.js里,把bcrypt.hash的第一个参数改成newContact.password,同时记得把错误传递给回调,方便路由处理:
module.exports.addRegistry = function(newContact,callback) { bcrypt.genSalt(10, (err,salt) => { if (err) return callback(err); // 提前处理salt生成错误 // 正确写法:传入密码字符串 bcrypt.hash(newContact.password, salt, (err,hash) => { if (err) return callback(err); newContact.password = hash; newContact.save(callback); }); }); }
步骤3:修复重复定义的方法(可选但重要)
你的contact.js里有两个同名的getUserById方法,第二个会覆盖第一个,导致根据ID查询用户的功能失效,建议重命名第二个方法:
module.exports.getUserById = function(id,callback) { Contact.findById(id,callback); } // 重命名为getUserByEmail,因为你的Schema里没有username字段 module.exports.getUserByEmail = function(email,callback) { const query = {email_id: email} Contact.findOne(query,callback); }
修改完成后重启你的服务器,再用Postman发送POST请求,应该就能正常创建联系人并完成密码哈希了。
内容的提问来源于stack exchange,提问作者user9705886
相关产品推荐
相关产品推荐

