Quantcast
Channel: Express.js req.body undefined - Stack Overflow
Viewing all articles
Browse latest Browse all 54

Answer by Mayur for Express.js req.body undefined

$
0
0

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}));app.use(app.router); // Route will be at the end of parser

And remove bodyParser (in newer version of express it is not needed)

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")})

Viewing all articles
Browse latest Browse all 54

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>