NextJS API接口无法获取req.body问题求助
解决Next.js API接口中DELETE请求无法获取req.body的问题
核心原因与修复方案
1. 请求Content-Type不匹配或格式错误
从你提供的请求截图来看,请求体是纯字符串而非JSON格式,但Next.js默认的body解析器只处理application/json类型的请求,这会导致req.body为空。
两种修复路径:
调整客户端请求:将请求体改为JSON格式,并设置正确的请求头:
// 客户端请求示例 fetch('/api/your-delete-endpoint', { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ postId: '你的帖子ID' }) // 或直接JSON.stringify(postId) })对应API中修改获取方式:
// 若发送的是{ postId: xxx }格式 const { postId } = req.body; // 若发送的是纯字符串JSON const postId = req.body;API端手动解析纯文本请求体:如果无法修改客户端,在API路由中手动读取请求流:
export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method === "DELETE") { // 手动解析纯文本body let postId = ''; await new Promise<void>((resolve) => { req.on('data', (chunk) => { postId += chunk.toString(); }); req.on('end', resolve); }); const session = await getServerSession(req, res, authOptions) if (!session) { return res.status(401).json({ message: "Please sign in" }) } if (!postId) { return res.status(400).json({ message: "Post ID is missing", body: postId }) } try { const result = await prisma.post.delete({ where: { id: postId } }) res.status(200).json(result) } catch (err) { res.status(500).json({ message: "Error has occurred while deleting the post", body: postId}) } } }
2. 检查Next.js body解析器配置
如果你的next.config.js中自定义了API配置,确认是否禁用了默认body解析器或限制了请求大小:
// next.config.js module.exports = { api: { bodyParser: { sizeLimit: '1mb', // 确保大小足够容纳请求体 }, // 若设置了bodyParser: false,必须手动解析请求体 }, }
内容的提问来源于stack exchange,提问作者Aditya
相关产品推荐
相关产品推荐

