Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize arrays/objects posted to my NodeJS/Express web app?

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?

like image 225
Jonathan Avatar asked Oct 20 '22 14:10

Jonathan


1 Answers

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());
like image 103
robertklep Avatar answered Oct 23 '22 05:10

robertklep