基于MERN栈的用户认证系统MongoDB写入400错误求助
MERN用户认证数据写入MongoDB问题修复方案
一、前端React表单核心问题
密码字段拼写错误
密码输入框的value属性拼写错误,导致密码无法正确绑定到state:// 错误 <Components.Input type="password" name="password" value={createUser.passord} placeholder="Password" onChange={handleInput}/> // 修复后 <Components.Input type="password" name="password" value={createUser.password} placeholder="Password" onChange={handleInput}/>请求数据嵌套错误
axios.post传递了嵌套对象{createUser},导致后端收到的是{createUser: {name: "...", ...}}结构,无法匹配mongoose的字段验证规则:// 错误 const rep = await axios.post('http://localhost:4040/user', {createUser}, { headers: { 'Content-Type': "application/json", } }) // 修复后 const rep = await axios.post('http://localhost:4040/user', createUser, { headers: { 'Content-Type': "application/json", } })年龄输入框无change事件
age输入框缺少onChange绑定,修改年龄无法同步到state:// 错误 <Components.Input type="number" name="age" value={createUser.age} placeholder="Confirm Password" /> // 修复后 <Components.Input type="number" name="age" value={createUser.age} placeholder="Age" onChange={handleInput}/>异步请求写法冗余且错误
混用await和.then/.catch冗余,且错误捕获中属性名拼写错误:// 修复后的handlesubmit async function handlesubmit(event){ event.preventDefault(); console.log(createUser); try{ const response = await axios.post('http://localhost:4040/user', createUser, { headers: { 'Content-Type': "application/json", } }); console.log(response.data); } catch(err){ console.log(err.response?.data || err.message); } }
二、后端Mongoose模型问题
- pre-save钩子语法错误
密码哈希代码未正确调用bcrypt.hash,且注释了依赖引入,导致执行报错。如需启用密码哈希,恢复依赖并修复钩子:
若暂时不需要哈希,可直接删除该钩子代码。// 恢复bcrypt引入 const bcrypt = require('bcryptjs'); // 修复pre-save钩子 userSchema.pre('save', async function(next){ const user = this; if(user.isModified('password')){ user.password = await bcrypt.hash(user.password, 8); } next(); });
三、调试建议
- 后端控制器新增打印,确认接收的数据结构:
exports.createUser = async (req,res) => { try{ console.log('Received data:', req.body); const user = new User(req.body); await user.save(); return res.status(201).json({success: true, user}); } catch(e){ console.log('Save error:', e); return res.status(400).json({success: false, message:e.message}); } } - 前端提交前检查
createUser对象的所有字段是否完整,避免空值触发必填验证错误。
内容的提问来源于stack exchange,提问作者Henry Nyonyo
相关产品推荐
相关产品推荐

