In Rails, if you have a form with underscores, it will assume a nested layout structure in params:
<input type="text" name="person_first" />
<input type="text" name="person_last" />
On the server, you'll get:
params #=> { person: { first: "Tom", last: "Hanks" } }
When I'm using Express.js in node.js, bodyparser doesn't seem to do the same thing. Looking at the code for bodyparser, it just runs the JSON parser on it, resulting in:
params #=> { person_first: "Tom", person_last: "Hanks" } }
Is there some way I can get the nested form data, like in Rails, when I'm using Express? Is there a library that enables me to do this?
If you are using express.bodyParser
you can use array notation to pass nested data.
Add express.bodyParser
middleware before your controllers.
app.use(express.bodyParser());
Now you can use this notation in your html code:
<input type="text" name="person[first]" />
<input type="text" name="person[last]" />
or
<input type="text" name="person[name][first]" />
<input type="text" name="person[name][last]" />
The key here is setting extended: true
app.use(bodyParser.urlencoded({
extended: true
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With