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

注册接口无法返回已存入数据库的用户信息,如何解决?

问题原因

你当前的代码无法返回存入数据库的用户信息,核心原因是MySQL的INSERT操作返回的结果对象不包含刚插入的行数据。你代码里的results[0]是undefined,因为results只包含插入操作的元数据(比如affectedRows、insertId),没有用户的具体信息。

解决方案

要解决这个问题,你需要在插入用户成功后,主动查询刚创建的用户记录,再返回给前端。同时建议你将嵌套的回调替换为async/await,让代码逻辑更清晰,避免回调地狱。

以下是修改后的完整代码:

app.post("/api/sign-up", async function (req, res) {
  try {
    // 检查用户是否已存在
    const [existingUsers] = await dbConn.query(
      `select * from accounts where email = ?`,
      [req.body.email]
    );

    if (existingUsers.length !== 0) {
      return res.send({
        error: true,
        message: "User exists",
      });
    }

    // 处理密码哈希
    const { email, phone, password } = req.body;
    const hashPass = await bcrypt.hash(password, 12);
    const fullname = null; // 用null而非字符串"NULL",对应数据库的NULL值

    // 插入新用户
    await dbConn.query(
      `insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
      [email, phone, hashPass, fullname]
    );

    // 查询刚创建的用户信息(注意不要返回密码哈希)
    const [newUser] = await dbConn.query(
      `select email, phone, fullname, id from accounts where email = ?`,
      [email]
    );

    // 返回结果
    return res.send({
      error: false,
      data: newUser[0],
      message: "User created Successfully",
    });
  } catch (error) {
    // 统一处理错误
    console.error(error);
    return res.send({
      error: true,
      message: "Server error",
    });
  }
});
关键改动说明
  • 替换嵌套回调为async/await,简化代码结构,错误处理更集中
  • 插入完成后,通过email查询刚创建的用户,确保获取到最新的数据库记录
  • 查询用户时排除password字段,避免返回敏感的密码哈希
  • 将字符串"NULL"改为null,符合数据库NULL值的正确传递方式
  • 统一使用参数化查询(?占位符),避免SQL注入风险(你之前的select查询用了dbConn.escape,但参数化查询更安全简洁)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:05:25