Home  >  Q&A  >  body text

req.body is undefined when using DELETE method in Next.js

I don't really know why, but when I try to get the data and put it into the response body, it says undefined (in the console). I have two almost identical components. One uses the POST method and returns a populated body, the other uses the DELETE method and returns an undefined body. I'm using Prisma architecture.

This is a POST that can be run and returns the API body

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 the beginning of the API of this function, const { id_product } = req.body is valid.

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}
    })

This is the problem I'm having, the components are basically the same except for the methods:

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, 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 few hours now with absolutely no progress.

P粉652523980P粉652523980262 days ago382

reply all(2)I'll reply

  • P粉477369269

    P粉4773692692024-01-03 20:14:48

    This was in effect until the most recent update. There are a lot of questions on GIthub, but I don't know if the maintainers of Next.js have responded yet. Currently it's preventing us from updating. I know this isn't typical, but this is a breaking change for Next.js and I don't want to migrate all DELETE endpoints :(.

    https://github.com/vercel/next.js/issues/49353

    https://github.com/vercel/next.js/issues/48096

    https://github.com/vercel/next.js/issues/48898

    reply
    0
  • P粉609866533

    P粉6098665332024-01-03 18:43:13

    delete The request does not contain a body. If you need to include a body in this request, you can try using the patch method

    reply
    0
  • Cancelreply