嗨,我一直处于这个问题的不确定状态。我正在尝试使用update方法来更新我的URL shortener项目中的点击迭代。迭代会在数据库中更新,但不会反映在前端。我原以为它会在获取后在then()函数中更新,但后来似乎没有放在then()函数中。我的问题是,代码是否有问题,或者有没有其他方法可以让它到达then()?
客户端(React)
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);
});服务器端(Mongoose)
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}`);
});
});发布于 2021-05-01 21:48:43
您的服务器在收到客户端的请求后没有做出响应,因此连接几乎处于不确定状态,因为缺少更好的词语。您需要向客户端发送响应
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你需要添加两个the才能得到你想要的数据。但是在您的例子中,您不想获取数据,所以应该这样做
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);
});此外,您实际上应该将后端链接作为代理值添加到您的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),
})https://stackoverflow.com/questions/67346553
复制相似问题