Next.js Discord

Discord Forum

Trying to POST error: req.json is not a function

Unanswered
Orange-tailed bumble bee posted this in #help-forum
Open in Discord
Orange-tailed bumble beeOP
I'm trying to post data to my backend with fetch API and the app router.
Here's my front code:
const { prompt } = values;
const response = await fetch('/api/message', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(prompt),
});

And here's my back code (at /app/api/message/route.ts):
export async function POST(
  req: NextRequest,
  res: NextApiResponse<ResponseData>,
) {
  const body = await req.json();
  const { prompt } = body;
  
  /// more code
}

I'm getting an error saying that req.json is not a function.
I tried using req.body but it didn't work (I got a ReadableStream).
I don't know why it's not working and I'd like to know what I should change.

13 Replies

Barbary Lion
@Orange-tailed bumble bee your req seems to be a formdata
So do something like req.FormData(), I had the same issue
or something like that
there is a stackoverflow answer I saw on that which said ReadableStream
@Orange-tailed bumble bee You shouldn't be taking res as an argument. Only the req.

Rest looks fine to me.
Barbary Lion
@Orange-tailed bumble bee did u fix it
Orange-tailed bumble beeOP
Thanks but I already fixed it (I installed Axios and it worked). I'll try with formData to see if I can remove axios.
Barbary Lion
@Orange-tailed bumble bee how did axios fix it
Maybe you don't have to do the req.json() part
Nextjs may parse the JSON automatically
So you can do req.body directly
Orange-tailed bumble beeOP
I tried to do req.body before but it didn't work but I'll try again
Giant panda
We discourage using Axios with Next because you cannot use certain features that Next provides. More info here: https://www.adios-axios.com/