Question

I'm writing an app in NodeJS/ExpressJS.

I have a form like this:

<form method="post" action="/sendinfo">
    <label>Name</label>
    <input type="text" name="name" />

    <label>Address</label>
    <input type="text" name="address[number]" />
    <input type="text" name="address[street]" />
    <input type="text" name="address[suburb]" />
    <input type="text" name="address[postcode]" />

    <label>Phones</label>
    <input type="text" name="phones[0]" />
    <input type="text" name="phones[1]" />
</form>

Here's my route:

app.post('/sendinfo', function (req, res) {

    // ...code to save the contents of req.body to the database...

    res.render('done');
});

When the form gets submitted, my req.body looks like this:

{
    "name": "Jonathan",

    "address[number]": "1",
    "address[street]": "Test St",
    "address[suburb]": "TestSuburb",
    "address[postcode]": "1234",

    "phones[0]": "12345678",
    "phones[1]": "87654321"
}

But I want it to instead look like this, with the values nested inside properties or arrays:

{
    "name": "Jonathan",

    "address": {
        "number": "1",
        "street": "Test St",
        "suburb": "TestSuburb",
        "postcode": "1234",
    },

    "phones": [
        "12345678",
        "87654321"
    ]
}

How can I do this?

Was it helpful?

Solution

Or use the urlencoded middleware (place it before any of your routes):

app.use(express.urlencoded());
...
app.post('/sendinfo', function(req, res) {
  // req.body will now contain the object you described
  ...
});

Updated July 16, 2017

urlencoded removed from express node module in the latest version so please use this for now

const bodyParser = require("body-parser");

    /** bodyParser.urlencoded(options)
     * Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
     * and exposes the resulting object (containing the keys and values) on req.body
     */

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

    /**bodyParser.json(options)
     * Parses the text as JSON and exposes the resulting object on req.body.
     */
    app.use(bodyParser.json());

OTHER TIPS

Figured out how.

Just needed to install the querystring package:

`npm install qs --save`

Then call it like this:

app.post('/sendinfo', function (req, res) {
    var qs = require('qs');
    var deserializedBody = qs.parse(qs.stringify(req.body));

    // ...code to save the contents of deserializedBody to the database...

    res.render('done');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top