Código Express/Nodo:
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); });código de reacción
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)} /> Mensaje de error:
ELIMINAR http://localhost:5000/inventory/62716639288c1342383e563a 404 (No encontrado)
No capturado (en promesa) SyntaxError: token inesperado < en JSON en la posición 0
No puedo encontrar nada malo. Pero no está funcionando.
Primero, console.log qué se envía exactamente al servidor, qué recibe, para comprender qué está pasando. Esto lo ayudará a rastrear el error (eche un vistazo de cerca al archivo console.log que he puesto a continuación):
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)} />Además, depure el backend con algunos console.logs más para ver qué sucede en ese lado. Junto con los registros, coloque una captura de prueba alrededor de la operación de espera para ver si algo se rompe:
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); });Estos registros lo ayudarán a identificar dónde algo sale mal y conduce al error que ve en la consola.