Be the first user to complete this post

  • 0
Add to List

Accessing the request body and session in nodejs using express

This is one of the issues that I ran into during my early days with nodejs. When you create a route handling function in nodejs, you would expect that if it a POST request, you would be able to access the body from req.body. However, it does not seem to be that straightforward. If you are a do-it-yourself person instead of using any bootstrapping commands from express, you might find yourself very frustrated until you find a solution. We built a simple starter kit for ourselves will everything preconfigured so that you can quickly launch experimental projects in a snap. If you have any doubts when reading this post, refer back to it, clone it and run it on your own machine to check it out.

Accessing the request body

Using express 4.0, in order to access the body of a post request, you need to have a minimal setup for your middleware. Note that there is no certainity if this will be relevant for all future versions of express but you can at least get the ball rolling for express 4.0. Include the body-parser middleware node module in your package.json
npm install body-parser --save

Now add the following lines in your app.js file somewhere in between the other middleware, preferably at the top, just after you declare your app.
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

Accessing the session

While at it, you probably also want to make sure that you can access the session. Even that does not come built in. You gotta include middleware modules for it the same way do you do it for accessing the request body.
npm install express-session --save
Then add the following lines to your middleware in app.js
app.use(session({
    secret: config.SESSION_SECRET ,
    saveUninitialized: true,
    resave: true
}));
Now you can access the body and the session using req.body and req.session (assuming that req is the name of your request paramter) The app.js file in the starter kit has it all if you are still confused about where to add these lines. Keep an eye on the official documentation for express.session and express.bodyparser for any changes.



Also Read:

  1. What is an npmignore file and what is it used for
  2. How to publish a package on npm
  3. Error: can not find module 'underscore'
  4. Creating a simple event emitter using nodejs