11

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:

enter image description here

1 Answer 1

24

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',
    }),
  })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.