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

Next.js 13路由处理器无法读取按钮组件请求体的问题

Next.js 13路由处理器无法读取请求体的解决方案

问题根源分析

  1. 客户端请求体格式错误
    你在fetch请求中使用JSON.parse('{"hello":"world"}')生成请求体,这会把JSON字符串转为JavaScript对象,但fetch API的body参数要求传入可直接发送的序列化数据(比如JSON字符串),直接传对象会被默认处理为[object Object],导致后端无法解析出有效JSON。

  2. 后端请求体读取方式错误

    • request.body是ReadableStream类型,直接用JSON.stringify打印只会输出流的结构,无法获取实际请求内容。
    • 请求体流只能被读取一次,如果你先尝试访问request.body再调用await request.json(),第二次读取会因为流已被消费而得到空数据。

修正后的代码

客户端Button组件

'use client'

export default function Button() {
    const handleClick = () => {
        const requestOptions = {
          method: "POST",
          body: JSON.stringify({"hello":"world"}), // 改用JSON.stringify序列化对象
          headers: { "content-type": "application/json"}
        }
        fetch("/api/create", requestOptions)
          .then((res)=>res.json())
          .then((data)=>console.log(data))
          .catch((err)=>console.log(err))
      }
  return (
    <button onClick={handleClick}>click</button>
  )
}

路由处理器

import { NextResponse } from 'next/server';
 
export async function POST(request) {
  // 先读取并缓存请求体,避免重复消费流
  const requestBody = await request.json();
  console.log(requestBody); // 此时会正确输出{"hello":"world"}
  
  return NextResponse.json({ "test": "123" });
}

验证说明

修正后点击按钮,后端控制台会正确打印{"hello":"world"},客户端也能正常接收返回的{"test":"123"}并输出到控制台。

内容的提问来源于stack exchange,提问作者Rohit Handique

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:05:10