Be the first user to complete this post

  • 0
Add to List

Access the request body of a post request in your nodejs - expressjs app.

One of the first hurdles that you will most likely need to cross in express is when you want to access the HTTP post body of a request, but you just cant seem to find it. Well, the answer lies in setting up a middleware function that creates a property called body on the request object that you can then make use of in your route handling function.

The Packages

As of this writing, in express 4.x, you gotta do the following. Install the body-parser package in your dependencies
npm install body-parser --save

The Application Code

If you have an app.js or an index.js which acts as the starting point for your application, include the following lines in your middleware before you define your route handling functions.
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
Hereafter, you should be able to access the POST body in all of your your routes as shown below
myRouter.post('/somePattern',function(req, res, next){
    console.log(req.body);
});
You can also read more about the other options in the github readme here.



Also Read:

  1. set the default node version using nvm
  2. Organizing your expressjs routes in separate files.
  3. Resolved - Error: listen eaccess using nodejs and pm2
  4. Setup passportjs for local authentication and authorization using expressjs
  5. Dynamic module loading with require