11

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?

1 Answer 1

22

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
}));
Sign up to request clarification or add additional context in comments.

2 Comments

can we have a dot notation for eg person.first or person.name.first. or is there a parser which would do that
Do we have nested attributes like this in Koa2 too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.