Next.js中DELETE请求req.body为undefined问题求助
解决DELETE请求中req.body为undefined的问题
核心原因
Next.js 默认会自动解析 POST 请求的 JSON 体,但对于 DELETE 这类非标准带体的请求,默认配置下不会自动解析请求体;另外,HTTP 规范虽允许 DELETE 带请求体,但部分服务器或框架处理时会忽略,因此更稳妥的方式是通过 URL 查询参数传递标识数据。
方案1:用URL查询参数传递数据(推荐)
这种方式符合 HTTP 最佳实践,也能避免请求体解析问题。
前端组件修改
type ProductProps = products; export default function ProductItem({ id_product, description, publication_date, author, name, link_image, price, }: ProductProps) { const onDeleteFromCart = async () => { let response = await fetch(`/api/deleteFromCart?id_product=${id_product}`, { method: "DELETE", }); if (response.ok) { toast.success(`${name} was succesfully removed from your cart`) } else { toast.error(`Error`); } }; }
后端API修改
async function handleDelete(req: NextApiRequest, res: NextApiResponse) { const session = await getServerSession(req, res, authOptions); const client = connexion() const { id_product } = req.query; 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: Number(id_product) // 转换为数字类型匹配Prisma字段 } }); // 后续删除逻辑... }
方案2:显式配置body解析(需保留请求体传递时使用)
如果一定要通过请求体传递数据,需手动启用 DELETE 请求的 body 解析:
- 安装依赖
npm install body-parser
- 修改API路由文件(
deleteFromCart.ts)
import bodyParser from 'body-parser'; import { getServerSession } from "next-auth/next"; import { authOptions } from "../auth/[...nextauth]"; import { connexion } from "../../../lib/prisma"; // 禁用Next.js默认的body解析,手动配置 export const config = { api: { bodyParser: false, }, }; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'DELETE') { // 显式解析JSON请求体 bodyParser.json()(req, res, async () => { 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 } }); // 后续删除逻辑... }); } else { res.setHeader('Allow', ['DELETE']); res.status(405).end(`Method ${req.method} Not Allowed`); } }
内容的提问来源于stack exchange,提问作者huzaks
相关产品推荐
相关产品推荐

