網站搜尋

reactjs - 在 Next.js 中使用 fetch 的 delete 方法時 req.body為未定義


我真的不知道為什麼,但當我嘗試抓取數據並將其放入回應的主體時,它在控制台顯示為未定義。我幾乎有兩個相同的組件。一個使用 POST 方法並返回填充的主體,另一個使用 DELETE 方法並返回未定義的主體。我正在使用 Prisma 架構。

這是能正常運作並返回 API 主體的 POST

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

這是該功能的 API 開始,const { id_product }=req.body 可以使用。

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

而這正是我遇到困難的地方,這個組件基本上是相同的,除了方法:

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

這是 API,const {id_product}=req.body 是未定義的

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

我已經嘗試解決這個問題好幾個小時了,但一點進展都沒有。

答案#1

這在最近的一次更新之前都能正常運作。在 GitHub 上有很多相關問題,但我不知道 Next.js 的任何維護者是否回應過。目前這阻礙了我們的更新。我明白這不尋常,但這是 Next.js 的破壞性變更,我不想必須遷移我們所有的 DELETE 端點 :(

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

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

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

答案#2

delete 請求不包含主體,如果你需要在此請求中包含主體,可以嘗試使用 patch 方法