I have this as configuration of my Express server
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
But still when I ask for req.body.something
in my routes I get some error pointing out that body is undefined
. Here is an example of a route that uses req.body
:
app.post('/admin', function(req, res){
console.log(req.body.name);
});
I read that this problem is caused by the lack of app.use(express.bodyParser());
but as you can see I call it before the routes.
Any clue?
You can use express body parser.
First make sure , you have installed npm module named 'body-parser' by calling :
Then make sure you have included following lines before calling routes
express.bodyParser() needs to be told what type of content it is that it's parsing. Therefore, you need to make sure that when you're executing a POST request, that you're including the "Content-Type" header. Otherwise, bodyParser may not know what to do with the body of your POST request.
If you're using curl to execute a POST request containing some JSON object in the body, it would look something like this:
If using another method, just be sure to set that header field using whatever convention is appropriate.
Looks like the body-parser is no longer shipped with express. We may have to install it separately.
Refer to the git page https://github.com/expressjs/body-parser for more info and examples.
The Content-Type in request header is really important, especially when you post the data from curl or any other tools.
Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.
Building on @kevin-xue said, the content type needs to be declared. In my instance, this was only occurring with IE9 because the XDomainRequest doesn't set a content-type, so bodyparser and expressjs were ignoring the body of the request.
I got around this by setting the content-type explicitly before passing the request through to body parser, like so: