1

I'm trying to log all the data and then return it as a response.

app.post('/data', (req, res) => {
  const data = req.body
  console.log(data)
  return res.json({
    data
  })
})

I'm sending data with Postman. In the Body tab I have "raw" selected and "JSON (application/json)". Headers tab is Content-Type application/json. I'm sending this:

    {
      "aa": 23
    }

When I click send button all I get is an empty object and the data variable is undefined in my console.log. How to fix it? I double checked everything. It should work, but it doesn't.

1
  • 4
    Did you install middleware to handle post request data, such as body-parser? Commented Sep 25, 2017 at 22:58

2 Answers 2

1

It seems like you're passing an invalid value to res.JSON(). Try:

return res.json(data);
Sign up to request clarification or add additional context in comments.

2 Comments

Not necessarily, perfectly valid JS property shorthand
Now I got nothing in Body and data variable is still undefined in console.log.
1

Alright, I found the solution.

"As body-parser module is used to parse the body and urls, it should be called before any call to 'req.body...'."

So I did this:

import bodyParser  from 'body-parser'

const app = express()
app.use(bodyParser.urlencoded())
app.use(bodyParser.json())

app.post('/data', (req, res) => {
  const data = req.body
  console.log(data)
  return res.json({
    data
  })
})

And now it works fine.

Comments

Your Answer

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