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

注册功能报错:TypeError无法读取undefined的'Name'属性,求排查

问题分析与修复方案

报错TypeError: Cannot read properties of undefined (reading 'Name')的核心原因是服务器端req.body为undefined,无法读取其中的Name字段。结合你的前后端代码,主要存在以下几个问题:

前端代码问题及修复

  1. 表单默认提交与异步请求冲突
    你的form标签同时设置了action="/SignUp"、method="POST"和onSubmit={handleSubmit(onSubmit)},这会触发浏览器默认的表单提交(页面跳转),直接中断你写的fetch异步请求,导致后端根本收不到正确的请求体。

    • 修复:移除form标签的action和method属性,完全由react-hook-form的handleSubmit处理提交逻辑。
  2. 固定value导致无法收集用户输入
    所有input标签都设置了value="default value",这会覆盖react-hook-form的register绑定,导致用户输入的内容无法被收集到data对象中,发送给后端的始终是默认值,甚至可能因为受控组件逻辑错误导致data为空。

    • 修复:移除所有input的value="default value"属性。
  3. 请求路径大小写不匹配
    前端fetch的路径是http://localhost:3000/signup(全小写),但后端的注册路由是/SignUp(大小写混合),HTTP路由是大小写敏感的,这会导致请求无法匹配到正确的后端路由,后端接收不到请求体。

    • 修复:将fetch的路径改为http://localhost:3000/SignUp,和后端路由保持一致。

修改后的前端关键代码:

const onSubmit = async (data) => {
  const response = await fetch("http://localhost:3000/SignUp", { // 修正路径大小写
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
};

<form
  className="flex flex-col gap-6 mt-10 justify-center items-center h-[250px] absolute bottom-[17rem]"
  onSubmit={handleSubmit(onSubmit)}
> {/* 移除action和method */}
  <input
    name="Name"
    className="bg-[#1c1d1e] w-[30rem] h-[3rem] font-light text-sm pl-5"
    autoComplete="off"
    placeholder="NAME"
    type="text"
    {...register("Name")}
  /> {/* 移除value="default value" */}
  {/* 其余input同理移除value属性 */}
  <button
    className="text-sm font-semibold border-2 w-28 h-8 rounded-[5px]"
    type="submit"
  >
    SUBMIT {/* 移除NavLink,避免点击直接跳转,建议根据fetch响应处理跳转 */}
  </button>
</form>

后端代码问题及修复

  1. 简化中间件使用
    虽然你使用了bodyParser.json(),但可以替换为Express内置的express.json()(body-parser已被整合进Express),写法更简洁且功能一致。

    • 修复:替换bodyParser相关代码:
      // 移除const bodyParser = require('body-parser');
      app.use(express.json()); // 替换app.use(bodyParser.json());
      
  2. 添加错误捕获逻辑
    当前注册路由没有错误处理,若User.register失败会导致服务器崩溃,且无法给前端返回错误提示。

    • 修复:用try/catch包裹注册逻辑:
      app.post("/SignUp", async function (req, res) {
        try {
          console.log(req.body); // 现在应该能正确打印请求体
          const user = new User({
            name: req.body.Name,
            email: req.body.Email,
          });
          await User.register(user, req.body.Password);
          passport.authenticate("local")(req, res, function () {
            res.redirect("http://localhost:3001/");
          });
        } catch (err) {
          console.error(err);
          res.status(500).send("注册失败:" + err.message);
        }
      });
      

验证步骤

  1. 重启后端服务,确保修改后的代码生效。
  2. 前端输入内容后点击提交,查看后端控制台的req.body输出,确认能正确接收到Name、Email、Password字段。
  3. 检查数据库是否成功创建用户记录。

内容的提问来源于stack exchange,提问作者Thor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:02:47