3

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?

1
  • Please put some code, html + server files Commented Mar 5, 2017 at 15:22

1 Answer 1

12

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, it was helpful and I am a noobie in nodejs

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.