You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何获取POST请求体数据?字段返回undefined

解决Next.js API路由中req.body字段返回undefined的问题

以下是几种常见的排查和解决方法:

  • 确保请求体解析逻辑正常
    Next.js API路由默认不会自动解析JSON请求体,需手动配置或添加解析逻辑:

    • 方法一:启用内置的bodyParser配置
      import type { NextApiRequest, NextApiResponse } from 'next'
      
      // 启用默认的JSON解析
      export const config = {
        api: {
          bodyParser: {
            sizeLimit: '1mb', // 可根据实际需求调整大小限制
          },
        },
      }
      
      export const POST = async (req: NextApiRequest, res: NextApiResponse) => {
        const { timeEntries, violations } = req.body
        console.info(timeEntries, violations)
        res.status(200).json({ success: true })
      }
      
    • 方法二:手动使用body-parser解析
      import type { NextApiRequest, NextApiResponse } from 'next'
      import bodyParser from 'body-parser'
      
      // 禁用默认解析,手动处理
      export const config = {
        api: {
          bodyParser: false,
        },
      }
      
      export const POST = async (req: NextApiRequest, res: NextApiResponse) => {
        await new Promise((resolve, reject) => {
          bodyParser.json()(req, res, (err) => {
            if (err) reject(err)
            resolve(null)
          })
        })
      
        const { timeEntries, violations } = req.body
        console.info(timeEntries, violations)
        res.status(200).json({ success: true })
      }
      
  • 检查请求的Content-Type头
    前端发送请求时必须设置Content-Type: application/json,否则解析器无法识别JSON格式的请求体。示例fetch请求:

    fetch('/api/your-endpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ timeEntries: [], violations: [] }),
    })
    
  • 验证请求体格式正确性
    确认发送的JSON没有语法错误,比如引号不匹配、多余逗号等,可通过在线JSON校验工具检查格式是否合规。

内容的提问来源于stack exchange,提问作者Jamie Hutber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:32:10