Friday 27 January 2012

Nodejs, express, jade and express's app.bodyParser() (nodejs 0.6.8)

So you're using the nodejs modules express and jade, and you're posting some form data, and you can't work out why 'req.body' is undefined.
You've read the docs, and you're using app.use(express.bodyParser()) and its not working still.
You're config looks like this :


But you need it the other way round, like this :


What you've done wrong is have the bodyParser() line after the app.router line.
Make sure you put the bodyParser() line before the app.router line, and you're gravy.

Note that after a twitter exchange with the express developers, this isn't a bug, but a feature of express's middleware config - a side-effect of the flexibility of their middleware injection.
This 'fix' works for me - I'm pretty new to express, so I've no idea on the impact on other middleware you may have configured.

I'm sure after more playtime with express I'll understand why routing config blat's body parsing if done in that order.
PS - If anyone does know the answer, I'd welcome a full explanation, or link to the docs on it.

No comments:

Post a Comment