You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于MERN栈的用户认证系统MongoDB写入400错误求助

MERN用户认证数据写入MongoDB问题修复方案

一、前端React表单核心问题

  1. 密码字段拼写错误
    密码输入框的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}/>
    
  2. 请求数据嵌套错误
    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",
      }
    })
    
  3. 年龄输入框无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}/>
    
  4. 异步请求写法冗余且错误
    混用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模型问题

  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:36:16