当我 fetch(url).then(console.log) 时,console.log 不执行

When I fetch(url).then(console.log), the console.log does not execute

您好,我一直对这个问题感到困惑。我正在尝试使用 update 方法来更新我的 URL shortener 项目中的点击迭代。迭代在数据库中更新,但随后并未反映在前端。我以为它会在获取后在 then() 函数中更新,但它似乎没有进入 then() 函数。我的问题是代码有问题还是有其他方法可以到达 then()?

客户端(反应)

const id = record._id;
    fetch(`http://localhost:3001/update/${id}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(updateData),
    })
      .then((res) => { <-- Not executing :(
        console.log("Update");
        // function to refresh the page
        handleRefresh(); 
      })
      .catch((err) => {
        console.log(err);
      });

服务器端(猫鼬)

urlControllerRouter.post("/update/:id", (req, res) => {
  const id = req.params.id;

  UrlModel.findById(id)
    .then((updateURL) => {
      updateURL.click = req.body.click;
      updateURL
        .save()
        .then(() => {
          console.log(`[UPDATE] ${updateURL}`);
        })
        .catch((err) => {
          console.log(`[UPDATE] ${err}`);
        });
    })
    .catch((err) => {
      console.log(`[UPDATE] ${err}`);
    });
});

您的服务器在收到来自客户端的请求后没有做出响应,因此由于缺少更好的词,连接几乎处于不稳定状态。 您需要向客户端发送响应

urlControllerRouter.post("/update/:id", (req, res) => {
  const id = req.params.id;

  UrlModel.findById(id)
    .then((updateURL) => {
      updateURL.click = req.body.click;
      updateURL
        .save()
        .then(() => {
         
          console.log(`[UPDATE] ${updateURL}`);
          res.status(200).json({
           message: updateURL
            })
        })
        .catch((err) => {
          console.log(`[UPDATE] ${err}`);
         res.status(500).json({
              message: err.message
          })
        });
    })
    .catch((err) => {
      console.log(`[UPDATE] ${err}`);
          res.status(200).json({
               message: err.message
            })
    });
});

顺便说一句,使用 fetch 你需要添加两个 then 来获取你想要的数据。 但是在您的情况下,您不想获取数据,所以可以这样做 所以像这样

fetch(`http://localhost:3001/update/${id}`, {
     method: "POST",
     headers: { "Content-Type": "application/json" },
     body: JSON.stringify(updateData),
   })
     .then(response => response.json())
     .then((res) => { <-- Not executing :(
       console.log("Update");

       // function to refresh the page
       handleRefresh(); 
     })
     .catch((err) => {
       console.log(err);
     });

此外,您实际上应该将后端 link 作为代理值添加到您的 package.json 中,作为对后端进行 API 调用的更好方法。

"name": "",
  "version": "",
  "main": "",
  "proxy": "http://localhost:3001", //note the proxy
  "license": "",
....

那么你只需要使用 fetch

fetch(`/update/${id}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(updateData),
    })