Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nested form data in express.js?

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?

like image 591
Wilhelm Avatar asked Nov 16 '12 17:11

Wilhelm


1 Answers

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]" />

Update for Express 4

The key here is setting extended: true

app.use(bodyParser.urlencoded({
  extended: true
}));
like image 88
Vadim Baryshev Avatar answered Nov 16 '22 04:11

Vadim Baryshev