Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

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

One of the first hur­dles 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 set­ting up a mid­dle­ware func­tion that cre­ates a prop­erty called body on the request object that you can then make use of in your route han­dling function.


The Pack­ages

As of this writ­ing, in express 4.x, you gotta do the following.

Install the body-parser pack­age in your dependencies

npm install body-parser --save

The Appli­ca­tion Code

If you have an app.js or an index.js which acts as the start­ing point for your appli­ca­tion, include the fol­low­ing lines in your mid­dle­ware before you define your route han­dling functions.

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

Here­after, 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.


Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...