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?
Express 4, has build-in body parser. No need to install separate body-parser. So below will work:
Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);
You can try adding this line of code at the top, (after your require statements):
As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions
If you are using some external tool to make the request, make sure to add the header:
Content-Type: application/json
Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately
and then do this in your code
No. You need to use
app.use(express.bodyParser())
beforeapp.use(app.router)
. In fact,app.use(app.router)
should be the last thing you call.