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?
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")
})
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,
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")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With