How can I deserialize arrays / objects hosted in my NodeJS / Express web application?

I am writing an application 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 is 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 is submitted, mine req.bodylooks 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 this to look like this, with 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?

+3
source share
2 answers

Or use middleware urlencoded(put it in front of any of your routes):

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

Figured out how.

Just need to install the query package:

`npm install qs --save`

Then name 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');
});
0
source

All Articles