5

I want to log all the query parameters which are passed to my endpoint. whenever they call me ie through GET , POST. i am able to print all the GET query params but struggling with POST params.

i used req.body but that doesnt work it just prints [Object object] even JSON.stringify didnt help.

Can any one point me to right source to look for it

SaNmm
  • 201
  • 1
  • 7
  • 14

1 Answers1

10

So POST parameters arrive in the HTTP request body, and this is handled as a stream of data chunks by node.js. So the first thing you must do is make sure you assemble the stream of chunks into a complete piece of data. Then you may want to parse it as either url encoded or JSON if that's what it is. The standard middleware for this is body-parser. You set it up like they say in the README:

const express    = require('express')
const bodyParser = require('body-parser')

const app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next()
})
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • bodyParser is deprecated: Look at this link https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4 – DAme Jul 26 '21 at 13:21
  • I'm not using the deprecated constructor in this code. From a quick scan the snippet still looks fine to me. If you find something deprecated please provide more detail as to what. This answer is seven years old so it's not exactly fresh in my mind. – Peter Lyons Jul 29 '21 at 15:06