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

Accessing the request body and session in nodejs using express

This is one of the issues that I ran into dur­ing my early days with nodejs. When you cre­ate a route han­dling func­tion in nodejs, you would expect that if it a POST request, you would be able to access the body from req.body. How­ever, it does not seem to be that straight­for­ward. If you are a do-it-yourself per­son instead of using any boot­strap­ping com­mands from express, you might find your­self very frus­trated until you find a solution.

We built a sim­ple starter kit for our­selves will every­thing pre­con­fig­ured so that you can quickly launch exper­i­men­tal projects in a snap. If you have any doubts when read­ing this post, refer back to it, clone it and run it on your own machine to check it out.

Access­ing the request body

Using express 4.0, in order to access the body of a post request, you need to have a min­i­mal setup for your mid­dle­ware. Note that there is no cer­tain­ity if this will be rel­e­vant for all future ver­sions of express but you can at least get the ball rolling for express 4.0.

Include the body-parser mid­dle­ware node mod­ule in your package.json

npm install body-parser --save

Now add the fol­low­ing lines in your app.js file some­where in between the other mid­dle­ware, prefer­ably at the top, just after you declare your app.

    extended: true

Access­ing the ses­sion

While at it, you prob­a­bly also want to make sure that you can access the ses­sion. Even that does not come built in. You gotta include mid­dle­ware mod­ules for it the same way do you do it for access­ing the request body.

npm install express-session --save

Then add the fol­low­ing lines to your mid­dle­ware in app.js

    secret: config.SESSION_SECRET , 
    saveUninitialized: true,
    resave: true 

Now you can access the body and the ses­sion using req.body and req.session (assum­ing that req is the name of your request paramter)

The app.js file in the starter kit has it all if you are still con­fused about where to add these lines.

Keep an eye on the offi­cial doc­u­men­ta­tion for express.session and express.bodyparser for any changes.

Ryan Sukale

Ryan is a UX engineer living in San Francisco, California.