lmenus lmenus -4 years ago 232
Node.js Question

ExpressJS request.params and request.body empty

Trying to send a simple post request, the

body
property is empty object
{}
. Anyone knows why?

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

app.set('port', process.env.PORT)

// Support JSON-encoded and encoded bodies.
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.post('/api/' + APIVersion.latest() + '/post-job', (req, res) => {
console.log(req.body)
res.json({ hey: 'hey' })
})

// Start the server.
app.listen(app.get('port'), err => {
if (err) {
return console.log('There was an error', err)
}

console.log(`Server running on port ${app.get('port')}`)
})

Answer Source

req.params is empty because your route doesn't specify any.

In Express, params refers to the route/url parameters. For example, if you wanted to have a route that allowed you to dynamically specify a user's last name, you may do:

app.get('/users/:last/info', (req, res) => {
    // ....
})

This would give the route a parameter of last, accessible by req.params.last.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download