Reputation: 111
so I am trying to delete an item from database using a button to call a delete function. everything works as they should and I can see the calling delete API log in the console however req.body is undefined I was wondering what am I doing wrong here.
here is the react part
export default function ProductPage({ items, adminToken }) {
const deleteItem = async (itemId) => {
const res = await fetch("/api/database/additems", {
method: "delete",
headers: { "content-type": "application/json" },
body: JSON.stringify(itemId),
});
const resResult = await res.json();
console.log(resResult);
};
if (adminToken) {
return (
<div className="min-h-screen flex flex-col bg-slate-200">
<Header />
this is the product page
<div className="flex flex-wrap ml-16">
{items.map((item) => (
<div key={item._id}>
<Link
href={{
pathname: "products/[id]",
query: { id: `${item._id}` },
}}
>
<a> item page</a>
</Link>
<button onClick={() => deleteItem(item._id)}>
Delete this item
</button>
and here is the API code
apiRouter.delete((req, res) => {
console.log("calling delete API");
console.log(req.body);
res.redirect("/products");
});
I have not implemented the deleting part yet since I can not get the body which contains the item unique id in the database.
Upvotes: 0
Views: 1175
Reputation: 11
DELETE
requires the body to have a data
parameter.
So you'll need your request to be
const res = await fetch("/api/database/additems", {
method: "delete",
headers: { "content-type": "application/json" },
body: JSON.stringify({ data: itemId }),
});
Upvotes: 1