为什么我的Next.js路由处理程序无法从按钮组件读取请求体?

ux6nzvsh  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(179)

我无法从nexjs13中的路由处理程序读取请求体。这是我的按钮组件

'use client'

export default function Button() {
    const handleClick = () => {
        const requestOptions = {
          method: "POST",
          body: JSON.parse('{"hello":"world"}'),
          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) {
  
  console.log(JSON.stringify(request))
  console.log(JSON.stringify(request.body))
  console.log(await request.json())
  
  return NextResponse.json({ "test": "123" });
}

我希望发送的正文{"hello": "world"}被记录在控制台中。
这是控制台console output中记录的内容

hjzp0vay

hjzp0vay1#

你的代码中有两个问题

  • 当在按钮组件中使用fetch调用API时,你应该对数据进行字符串化而不是解析。
body: JSON.stringify({ hello: 'world' }),
  • 在next13中从route.js中的请求体读取数据
console.log(await request.json())

您的整个代码应类似于
按钮组件

'use client';

export default function Button() {
    const handleClick = () => {
        const requestOptions = {
            method: 'POST',
            body: JSON.stringify({ hello: 'world' }),
            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>;
}

route.js

export async function POST(request) {
    console.log(await request.json());

    return Response.json({ test: '123' });
}

相关问题