Next.js Discord

Discord Forum

Simple form data not reaching endpoint

Answered
Chinese perch posted this in #help-forum
Open in Discord
Chinese perchOP
The form is not reaching the endpoint. Im getting an empty object.
Answered by European sprat
View full answer

52 Replies

Chinese perchOP
This sends the form
route.tsx
import { NextResponse } from "next/server";

export async function POST(req: Request):Promise<NextResponse> {
    const res = await req.json()
    console.log(res)
    return new NextResponse("nice")
}
European sprat
try:

body: JSON.stringify({ username, password })
@European sprat try: `body: JSON.stringify({ username, password })`
Chinese perchOP
I have lots of fields, so I would prefer not to manually type those
European sprat
then send formData in the body
@European sprat then send formData in the body
Chinese perchOP
Without strigiify?
European sprat
correct
European sprat
Answer
@European sprat correct
Chinese perchOP
same result
ohh
wait
Do I have to refresh the page?
Manually?
Again?
- error SyntaxError: Unexpected number in JSON at position 1
Shall I remove the header?
nope
Not working
European sprat
show your updated code
Chinese perchOP
European sprat
and show the route handler
Chinese perchOP
import { NextResponse } from "next/server";

export async function POST(req: Request):Promise<NextResponse> {
    const res = await req.json()
    console.log(res)
    return new NextResponse("nice")
}
Its the same
European sprat
read the last link i sent which i said to use for formdata
European sprat
no you didn't
@European sprat no you didn't
Chinese perchOP
Uhh ok. My bad. Not with this specific combination of no headers and no stringify. Sorry!
I did indeed try it before, and it returned cannot parse formdata
So
Thanks!
European sprat
does it work now?
@European sprat does it work now?
Chinese perchOP
It does!
Quite simple
European sprat
awesome
Chinese perchOP
Thanks!
European sprat
you're welcome
@European sprat you're welcome
Chinese perchOP
btw, do I have to specify some type for eslint to understand?
It thinks res.get("username") is null. Whereas it is not
It returns the values
European sprat
well it might be null so you should say:

let username: string | null or something similar
Chinese perchOP
ohh
what abt
?
ts has the ? right?
for safe check I think?
European sprat
it can't know if it's null or not because it's a client side fetch
you can try string? but i'm not sure if that's considered "undefined" (as opposed to null)
oh well. It wasn't even a string
@Chinese perch oh well. It wasn't even a string
yeah it's File | string | null basically