Next JS API(应用程序目录)请求.json()出错

mxg2im7a  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(100)
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  const data = await request.json();

  console.log(data);
  return NextResponse.json({ foo: "boo" });
}

下一个版本=“下一个”:“13.4.2”
error:在await request.json()获取错误

error SyntaxError: Unexpected token  in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6571:19)
    at successSteps (node:internal/deps/undici/undici:6545:27)
    at node:internal/deps/undici/undici:1211:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
mrwjdhj3

mrwjdhj31#

此错误通常发生在您尝试从API端点获取body,但未在body中发送任何数据时。为了安全起见,在try catch中总是使用它

import { NextResponse } from "next/server";

export async function POST(request: Request) {
  try{
     const data = await request.json();
     console.log(data);
  }
  catch(e) {
     /* you error message */
  }
  return NextResponse.json({ foo: "boo" });
}

相关问题