Skip to content Skip to sidebar Skip to footer

In Express, Is It Possible To Post An Array Of Objects Without Ajax?

I am trying to submit an array of objects using a regular form, without AJAX, and am finding that instead of the request body being parsed into an array of objects it just has many

Solution 1:

When you make a POST request, with a regular form or with JavaScript, you are sending formatted text to the server.

You can't send an array, but you can send a text representation of an array.

None of the data formats supported by forms come with a standard method to represent an array of data.

A pattern (introduced by PHP) uses square brackets to describe array-like structures.

This is similar to what you are using, except you sometimes use JavaScript style dot-notation. Switch to purely using square-brackets.

name="attachment[1][uri]"

… but you need to decode that data format on the server.

To do that in Express 4 use:

var bodyParser = require("body-parser");
var phpStyleParser = bodyParser.urlencoded({ extended: true })

and

app.post('/example', phpStyleParser, function(req, res) {
    console.log(req.body);
    res.json(req.body);
});

Post a Comment for "In Express, Is It Possible To Post An Array Of Objects Without Ajax?"