我真的不知道為什麼,但是當我嘗試獲取資料並將其放入回應正文中時,它顯示未定義(在控制台中)。我有兩個幾乎相同的組件。一種使用 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 } })
我已經嘗試解決這個問題幾個小時了,但完全沒有進展。
這在最近更新之前一直有效。 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
delete
請求不包含正文,如果您需要在此請求中包含正文,可以嘗試使用patch
方法