'React not finding Express server delete request. (MERN delete problem)
Express/Node Code:
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);
});
React Code
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)}
/>
Error Message:
DELETE http://localhost:5000/inventory/62716639288c1342383e563a 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I can't find anything wrong. But it's not working.
Solution 1:[1]
First, console.log what exactly is being sent to the server, what you receive, in order to understand what's going on. This will help you track down the error (take a close look at the console.log I've put below):
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)}
/>
Also, debug the backend with a few more console.logs to see what's happening on that side. Along with the logs, put a try catch around the await operation to see if anything breaks:
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);
});
These logs will help you pinpoint, where something goes wrong and leads to the error that you see on the console.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
