vineet sah vineet sah - 5 months ago 40
Node.js Question

How to work body parser and express session NodeJs Middleware functions

I have started to working on MEANJS technology. I have been not clear about some functions of body-parse and express-session. I also go through their official site but not still clear. That functions are:-


bodyParser.urlencoded({
extended: true });

bodyParser.json()

expressSession({ resave: true, saveUninitialized: true, })


In some place it will
bodyParser.urlencoded({ extended: false })
and
expressSession({ resave: false, saveUninitialized: false, })
. Now when use these
boolean
, please explain this with example. So it will more clear.

Answer

Middleware body-parser:

In general this middleware will parse the bodies of incoming HTTP requests and populate the req.body property which is then available in your routes and middlewares.

body-parser provides different parsers for different types of request bodies. If you write the following:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

The first app.use() will include the JSON body parser and the second one will include the URL-encoded form body parser. The parsers you will need depend on the request types your server has to deal with. The difference regarding extended: false and extended: true is already explained in this answer.

Middleware express-session:

This middleware provides an easy way to handle sessions and session data in your express app. The two configuration properties resave and saveUninitialized influence the way express-session stores the session data of your users.

Example: Assume a new user is visiting your web site. express-session detects that this user does not have a session yet so it will create a new one which only contains a session ID and no data. If you set saveUninitialized: true this session will be stored in your session store without containing any real session data. saveUninitialized: false will store the session as soon as it actually contains some values. (simply said)

Example: Now assume a user with an existing session is visiting your web site. Some resources are requested but the user's session data does not change. resave: true will store the unchanged data anyway whereas resave: false will not.

Summary: Setting app.use(expressSession({resave: false, saveUninitialized: false})); will reduce the number of times your session store will be accessed which is a benefit regarding hardware resources and performance. So in most cases you will want to set them to false.

Comments