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?
This saved my day.
Wasted a lot of time:
Depending on Content-Type in your client request
the server should have different, one of the below app.use():
Source: https://www.npmjs.com/package/body-parser#bodyparsertextoptions
Example:
For me, On Client side, I had below header:
So, on the server side, I used:
Then, req.body worked fine.
This occured to me today. None of above solutions work for me. But a little googling helped me to solve this issue. I'm coding for wechat 3rd party server.
Things get slightly more complicated when your node.js application requires reading streaming POST data, such as a request from a REST client. In this case, the request's property "readable" will be set to true and the POST data must be read in chunks in order to collect all content.
http://www.primaryobjects.com/CMS/Article144