I really don't know why, but when I try to fetch data and put it in the body of my response, it says undefined (in the console). I have almost 2 identical components. One uses a POST method and returns a populated body, the other uses a DELETE method and returns an undefined body. I am using a Prisma schema.
This is the POST that works and returns a body for the API
export default function Product({
id_product,
name,
link_image,
price,
}: ProductProps) {
const [test, testing] = useState(false);
const { push: relocate } = useRouter();
const onAddToCart = async () => {
let response = await fetch("/api/addToCart", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id_product: id_product,
}),
});
if (response.ok) {
toast.success(`${name} was added to the cart`);
} else {
toast.error(`${name} is already in your cart`);
}
};
This is start of the API for that function, const { id_product } = req.body works.
async function handlePost(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
const client = connexion()
const { id_product } = req.body;
const user = await client.user.findFirst({
where: { email: session?.user?.email || undefined}
})
let cart = await client.cart.findFirst({
where: {id_user: user?.id_user}
})
And this is what I'm having trouble with, the component is basically the same, except the method :
type ProductProps = products;
export default function ProductItem({
id_product,
description,
publication_date,
author,
name,
link_image,
price,
}: ProductProps) {
const onDeleteFromCart = async () => {
let data = {
id_product: id_product
}
let response = await fetch("/api/deleteFromCart", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (response.ok) {
toast.success(`${name} was succesfully removed from your cart`)
}
else {
toast.error(`Error`);
}
};
This is the API for, const {id_product} = req.body is undefined
async function handleDelete(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
const client = connexion()
const { id_product } = req.body
console.log(id_product)
const user = await client.user.findFirst({
where: { email: session?.user?.email || undefined}
});
let cart = await client.cart.findFirst({
where: {id_user: user?.id_user}
});
let cart_item = await client.cart_item.findFirst({
where: {
id_cart: cart?.id,
id_product: id_product
}
})
I've been trying to solve this problem for a couple of hours now and I didn't progress at all.
delete
requests doesn't contains body, you can try usingpatch
method instead if you need a body in this request