POST request returning 500 Internal Server Error Next.js

224 views Asked by At

I am trying to write a simple POST request in my next.js app and getting a 500 Internal Server error when testing in Postman. I've written a GET request and that works fine.

Here is my basic code.

import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const body = await request.json();
  return NextResponse.json(body);
};

Here is the error in my terminal: тип SyntaxError: Unexpected non-whitespace character after JSON at position 31 at JSON.parse () at parseJSONFromBytes (node:internal/deps/undici/undici:5329:19) at successSteps (node:internal/deps/undici/undici:5300:27) at fullyReadBody (node:internal/deps/undici/undici:1447:9) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async specConsumeBody (node:internal/deps/undici/undici:5309:7) at async POST (webpack-internal:///(rsc)/./app/api/projects/route.ts:11:18) at async /Users/austinwilliams/Desktop/portfolio-react/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:63251

I've tried removing the async and await, that will remove the error but the response is an empty object. Not sure how to troubleshoot knowing it is a promise and the function needs to by async.

When I remove the async await I get status 200 with an empty response object. enter image description here

2

There are 2 answers

3
Hummel On

Try this.

import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const body = request.body;
  return NextResponse.json(body);
}
1
Austin Williams On

My JSON object in postman had a syntax error.