Req.body is always empty or undefined
Answered
Cape lion posted this in #help-forum
Cape lionOP
I am trying to understand major changes in Next Js latest update. I am trying to create an api but unable to do so. Kindly Help Me
40 Replies
Cape lionOP
Okay
Cape lionOP
File Structure, Server and client side
you need to do request.json()
Cape lionOP
It is giving an error
@@ts-ignore
you need to debug it yourself
Cape lionOP
ok
@Cape lion It is giving an error
console.log(await request.text())what do you get
Cape lionOP
The entire body data
which is?
screenshot
Cape lionOP
{
"name":"abc",
"email":"ppp",
"password":"fkggjf"
}
"name":"abc",
"email":"ppp",
"password":"fkggjf"
}
But in text format
ok. now change to
console.log(await request.json())Answer
what do you get
Cape lionOP
entire data in json()
But earlier it was giving an error
Thanks for help
@joulev why it is req.json() rather tha req.body.json()?
Becuase i have created several other application using Next JS
But, i have always used req.body.json()
It used to work always
@Cape lion <@484037068239142956> why it is req.json() rather tha req.body.json()?
because here it is the native [
Request](https://developer.mozilla.org/en-US/docs/Web/API/Request/json) not the express-like NextApiRequest@Cape lion But, i have always used req.body.json()
no you didn't. you used
req.body NOT req.body.json()req.body.json() does not work in any nextjs versionsCape lionOP
hmm req.body
my other project
@joulev because here it is the native [`Request`](<https://developer.mozilla.org/en-US/docs/Web/API/Request/json>) not the express-like `NextApiRequest`
Cape lionOP
Is it new in this version?
@Cape lion Is it new in this version?
pages router then you use
app router then you use
req.body.userNameapp router then you use
req.json()because pages router uses NextApiRequest while app router uses the native Request
Cape lionOP
Okay
you have seen the native response before, it's the result of fetch that's why you have
not
const res = await fetch(...)
const json = await res.json()not
const json = res.bodynative request is the same
Cape lionOP
Thank you so much