Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive form data in an array in node.js using Express?

I want to create a form which makes a request of type POST and send the data to the node.js server (using express).

How can the form sent and received as an array in the server?

like image 867
Andrei Margeloiu Avatar asked Jan 31 '26 10:01

Andrei Margeloiu


1 Answers

PHP introduced an extension to the application/x-www-form-urlencoded data format that allows complex data structures to be encoded. Express has support for that format via the body-parser module.

Name the fields with [] at the end of the name.

<fieldset>
    <legend>What animals do you like?</legend>
    <label><input type="checkbox" name="animals[]" value="Cats"> Cats</label>
    <label><input type="checkbox" name="animals[]" value="Dogs"> Dogs</label>
    <label><input type="checkbox" name="animals[]" value="Tortoises"> Tortoises</label>
</fieldset>

Then, in express, use the body-parser middleware and turn on extended support.

app.use(bodyParser.urlencoded({ extended: true }))

When you read the request body, animals will be an array (or unset if none of the checkboxes were checked).

like image 135
Quentin Avatar answered Feb 03 '26 04:02

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!