skip to Main Content

I am using next js 13 route handler to get a login form data . I think I should be able to get it using formData method but it returns an empty object.
My login page in app/login/page.jsx:

export default function Page() {
    return (
        <div>
            <form action="/api" method="post" className="...">
                <input type="text" name="username" id="username" className="..." />
                <input type="password" name="password" id="username" className="..." />
                <input type="submit" id="submit" value="submit" className="..." />
            </form>
        </div>
    )
}

and app/api/route.js:

import { NextResponse } from 'next/server';

export async function POST(request):
    const data = request.formData();
    return NextResposne.json({ data })

and this is my response after submitting the form:

{"data":{}}

Any idea ? thanks

2

Answers


  1. You have to create a new object from Response and convert it to string if it’s not.

    import { NextApiRequest, NextApiResponse } from "next";
    
    export async function POST(req: NextApiRequest, res: NextApiResponse) {
    const data = await request.formData();
    return new Response(JSON.stringify(data))
    
    }
    

    Also, please don’t use ninja code it’s not a good way to code.

    And please add another security option to it, getting form data without analising the input data is so risky.

    Login or Signup to reply.
  2. .formData returns Promise

    (method) Body.formData(): Promise<FormData>
    

    You should await it:

    const data = await request.formData();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search