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

生成Google式备份代码后,前后端日志存在但MongoDB未存储的问题

问题诊断与解决

核心原因

前后端传递的字段名称不匹配:

  • 前端请求体中传递的备份码字段是backendCodes
  • 后端试图从req.body中解构读取backupCodes,但请求里根本没有这个字段,导致backupCodes变量为undefined
  • 由于你的MongoDB Schema定义backupCodes为[Number]类型,当传入undefined时,Mongoose会自动将其初始化为空数组存入数据库

解决方法(二选一即可)

方法1:修改前端代码,统一字段名为backupCodes

修改前端请求体的字段名,和后端保持一致:

signUpUser(email: string, password: string, backendCodes: number[]) {
    const url = "http://localhost:3000/signup/api"
    // 把backendCodes改成backupCodes
    const body = { email, password, backupCodes: backendCodes };

    console.log(body);

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post(url, body, { headers }).subscribe({
      next: value => console.log(value),
      error: error => console.log(error),
      complete: () => console.log("Complete")
    });
}

方法2:修改后端代码,读取正确的字段名

调整后端的解构逻辑,读取前端实际传递的backendCodes字段:

app.post("/signup/api", async (req, res) => {
  // 解构backendCodes,而不是backupCodes
  const { email, password, backendCodes } = req.body;
  console.log(req.body); 

  try {
    const newUser = new User({
      email: email,
      password: password,
      // 将backendCodes赋值给backupCodes字段
      backupCodes: backendCodes,
    });

    await newUser.save();
    console.log("Successful");
    res.status(200).json({ message: "User signed up successfully" });
  } catch (err) {
    console.log("Error: ", err);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

验证

修改后重新测试,数据库中的backupCodes字段就能正确保存前端传递的随机数字数组了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:06:22