![](/img/trans.png)
[英]Multiple filtered get request to my express backend [MERN (React + Express)]
[英]React not finding Express server delete request. (MERN delete problem)
快递/节点代码:
app.delete("/inventory/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await inventoryCollection.deleteOne(query);
res.send(result);
});
反应代码
const handleDelete = (id) => {
const url = `http://localhost:5000/inventory/${id}`;
fetch(url, { method: "Delete" })
.then((res) => res.json())
.then((data) => {
if (data.dataCount > 0) {
console.log("deleted");
const remaining = products.filter((service) => service._id !== id);
setProducts(remaining);
console.log(data);
}
});
}
<FontAwesomeIcon
icon={faTrashAlt}
className="delete-font"
onClick={() => handleDelete(product._id)}
/>
错误信息:
删除 http://localhost:5000/inventory/62716639288c1342383e563a 404(未找到)
未捕获(承诺)SyntaxError:意外令牌 < in JSON at position 0
我找不到任何错误。 但它不起作用。
首先,console.log 究竟发送给服务器的是什么,您收到了什么,以便了解发生了什么。 这将帮助您追踪错误(仔细查看我放在下面的 console.log):
const handleDelete = (id) => {
console.log("Am I sending the correct id?", id ); // <= debugging
const url = `http://localhost:5000/inventory/${id}`;
console.log("Is the URL formatted correctly?", url); // <=debugging
fetch(url, { method: "Delete" })
// .then((res) => res.json()) //Let's replace json() with text() to see the actual response in any case
.then((res) => res.text())
.then((data) => {
console.log("What exactly comes back from the server?", data); // <= debugging
if (data.dataCount > 0) {
console.log("deleted");
const remaining = products.filter((service) => service._id !== id);
setProducts(remaining);
console.log(data);
}
});
}
<FontAwesomeIcon
icon={faTrashAlt}
className="delete-font"
onClick={() => handleDelete(product._id)}
/>
此外,使用更多的 console.logs 调试后端以查看那边发生了什么。 与日志一起,在 await 操作周围放置一个 try catch 以查看是否有任何中断:
app.delete("/inventory/:id", async (req, res) => {
console.log("Is this endpoint ever get hit?"); <= debugging
const id = req.params.id;
console.log("Do I get the ID I expect?", id ); <= debugging
const query = { _id: ObjectId(id) };
try {
const result = await inventoryCollection.deleteOne(query);
console.log("What comes out of deleteOne operation?", result); <= debugging
} catch (e){
console.log("Ops! Something went wrong with the deleteOne operation"); <= debugging
}
res.send(result);
});
这些日志将帮助您查明哪里出了问题并导致您在控制台上看到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.