Be the first user to complete this post
|
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.jsonnpm install body-parser --save
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
app.use(session({
secret: config.SESSION_SECRET ,
saveUninitialized: true,
resave: true
}));
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:
- What is npm shrinkwrap and when is it needed
- Setup nginx with multi domain websites running on nodejs
- Send email using nodejs and express in 5 simple steps
- Unit test your Nodejs RESTful API using mocha
- Error: can not find module 'underscore'