Reputation: 3822
I've setup a simple api route in nextjs and am trying to parse the body for post request data but get "undefined" when I use the syntax console.log(req.body.name)
if I output to the console the request body console.log(req.body)
I get what looks like a plain string:
------WebKitFormBoundaryMJBujN4oNXLxcU96
Content-Disposition: form-data; name="name"
bilbo.com
------WebKitFormBoundaryMJBujN4oNXLxcU96
Content-Disposition: form-data; name="price"
2995
------WebKitFormBoundaryMJBujN4oNXLxcU96--
this is the function:
export default (req, res) => {
console.log(req.method);
console.log(req.body);
console.log(req.body.name);
res.status(200).json( { items: [ { req : req.method } ] } )
}
and the data in the request headers:
Upvotes: 11
Views: 14899
Reputation: 279
This question is quite old, but if someone else happens to end up here:
Per the documentation:
req.body - An object containing the body parsed by content-type, or null if no body was sent
This means if you want to parse req.body as JSON you have to set the 'Content-Type': 'application/json' header in the request header:
fetch(url, {
body,
method,
headers: new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
}),
})
Upvotes: 26