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

使用Async/await & Promise等待POST请求后获取新增用户失败问题

问题:创建用户后无法立即获取新用户列表

我在创建新用户并将其添加至数据库后,希望获取更新后的用户列表。但即便等待POST请求执行完成,刚创建的新用户也不会出现在GET请求返回的结果中,只有再次创建新用户时,才会返回上一次创建的用户。

前端实现尝试

方式一(Async/await)

createUser()
async function createUser(){
    const response = await fetch("http://localhost:3334/user", {
        method: "POST",
        body: JSON.stringify({
          name: name,
          password: password,
          email: email,
        }),
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        },
      })
      const data = await response.json()
      console.log(data)

      const fetchResponse = await fetch("http://localhost:3334/users")
      const fetchData = await fetchResponse.json()
      
      console.log(fetchData)
      
}

方式二(Promise链式调用)

fetch("http://localhost:3334/user", {
  method: "POST",
  body: JSON.stringify({
    name: name,
    password: password,
    email: email,
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
  },
}).then((response) => {
  if (response.status === 200) {
    return fetch("http://localhost:3334/users")
      .then((response) => response.json())
      .then((data) => console.log(data));
  }
});

后端Express POST接口代码

router.post('/user', (req, res) => {
    res.json({requestBody: req.body})
    bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
        db.query("INSERT INTO users (email, name, password) VALUES (?,?,?)", [req.body.email, req.body.name, hash], function(err, result) {
        if (err) throw err;
        console.log("Result: " + JSON.stringify(result));
      })
    });
})

问题原因

后端POST接口逻辑顺序错误:你先通过res.json()向前端返回了响应,之后才执行密码哈希和数据库插入操作。这导致前端收到POST成功响应时,新用户数据还没写入数据库,此时发起的GET请求自然查不到刚创建的用户。

解决方案

把res.json()移到数据库插入完成的回调函数内,确保只有当用户数据成功写入数据库后,再向前端返回响应。修改后的后端代码如下:

router.post('/user', (req, res) => {
    bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
        if (err) {
            return res.status(500).json({ error: '密码哈希失败' });
        }
        db.query("INSERT INTO users (email, name, password) VALUES (?,?,?)", [req.body.email, req.body.name, hash], function(err, result) {
            if (err) {
                return res.status(500).json({ error: '插入数据库失败' });
            }
            console.log("Result: " + JSON.stringify(result));
            // 数据库插入完成后再返回响应
            res.json({requestBody: req.body, message: '用户创建成功'});
        })
    });
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:55:16