3

I created a crud rest api with nodejs, am testing the api with postman. Any time I send a request using the "Body" in postman, req.body returns undefine. What could be the cause pls?

Joseph
  • 31
  • 1
  • 4

3 Answers3

6

A general mistake is to forget the body-parser NPM.

Below peace of code is showing how simple a server and API is created with Node.JS and Express. First install the NPM's

npm install body-parser express --save

And then try this piece of code:

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

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/test-url', (req, res) => {
    console.log(req.body)
    return res.send("went well")
})

app.listen(3000, () => {
    console.log("running on port 3000")
})
crellee
  • 855
  • 1
  • 9
  • 18
  • +1 - I had routes defined above the bodyparser and it returned undefined. Moving it below completed the call. – Faye Hayes Feb 28 '20 at 19:12
1

History:

Earlier versions of Express used to have a lot of middleware bundled with it. bodyParser was one of the middleware that came with it. When Express 4.0 was released they decided to remove the bundled middleware from Express and make them separate packages instead. The syntax then changed from app.use(express.json()) to app.use(bodyParser.json()) after installing the bodyParser module.

bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express like before. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.

The release history for 4.16.0 is here for those who are interested, and the pull request is here.

Okay, back to the point,

Implementation:

All you need to add is just add,

app.use(express.json());
app.use(express.urlencoded({ extended: true}));

Before route declaration, instead of,

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

And Express will take care of your request. :)

Full example will looks like,

const express       = require('express')
const app           = express()

app.use(express.json())
app.use(express.urlencoded({ extended: true}));

app.post('/test-url', (req, res) => {
    console.log(req.body)
    return res.send("went well")
})

app.listen(3000, () => {
    console.log("running on port 3000")
})
Mayur
  • 4,345
  • 3
  • 26
  • 40
0

Sometimes it happens as you are sending as a form-data from Postman, instead try x-www-form-urlencoded data. form data shows undefined but urlencoded data as a proper value. enter image description here

SUBHASIS MONDAL
  • 705
  • 9
  • 20