Next.js Discord

Discord Forum

POST request to Route Handler

Answered
Allegheny mound ant posted this in #help-forum
Open in Discord
Allegheny mound antOP
I have the following API endpoint using the App dir:

import { NextResponse } from 'next/server';

export async function POST(req: Request) {
    const formData = await req.formData();
    const name = formData.get('name');

    return NextResponse.json({ name: name });
}

Which works correctly when calling it from Postman.

However, when calling it in my code it does not:

const response = fetch(endpoints.api.widgets.create, {
            method: 'POST',
            body: JSON.stringify(values)
        })
            .then((res) => res.json())
            .then((data) => {
                console.log(data);
            })
            .catch((err) => {
                console.error(err);
            });


As it returns me the error error TypeError: Request.formData: Could not parse content as FormData.

I tried adding 'Content-Type': 'multipart/form-data; boundary=... to the request header.

But then it tells me error TypeError: Error: Unexpected end of form.

Any ideas?
Answered by European sprat
when you're calling it in code you're sending the data as JSON. if you want to read it as JSON you need to change the route handler to:

import { NextResponse } from 'next/server';

export async function POST(req: Request) {
    const { name } = await req.json();

    return NextResponse.json({ name });
}
View full answer

3 Replies

European sprat
when you're calling it in code you're sending the data as JSON. if you want to read it as JSON you need to change the route handler to:

import { NextResponse } from 'next/server';

export async function POST(req: Request) {
    const { name } = await req.json();

    return NextResponse.json({ name });
}
Answer
European sprat
if you actually want it to be formData then you need to send it as formData and not JSON
Allegheny mound antOP
Ah got it, thanks!