Express Parsing Array from POST
Asked Answered
I

4

13

Running an Express API, I'm struggling to parse data including an array of objects correctly when hitting a POST route.

A simplified version of the code -

var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false });

router.post('/', parseUrlencoded, function(req, res) {
    console.log(req.body);
});

Hitting the API with the following

{ name: "Object name", 
  arrayOfObjects: [
      { name: "Sub Object Name", subType: "Sub Object Type" }, 
      { name: "Sub Object Name 2", subType: "Sub Object Type 2" }
  ] 
}

Logs out

{ name: "Object name", 
  'arrayOfObjects[0][name]': "Sub Object Name",
  'arrayOfObjects[0][subType]': "Sub Object Type",
  'arrayOfObjects[1][name]': "Sub Object Name 2",
  'arrayOfObjects[1][subType]': "Sub Object Name",
}

I would like to receive this as an array, which is the case when using a PUT request.

I'm sure this possible using a configuration of bodyParser or similar, but I'm struggling to find a good solution.

Inbeing answered 7/9, 2017 at 18:9 Comment(0)
F
19

Ok, from your question I understand that you want to manipulate the POST Body like a json array then use qs library by making extended true

app.use(bodyParser.urlencoded({ extended: true }));
Forcefeed answered 7/9, 2017 at 18:15 Comment(0)
S
6

You can send an string instead of array and keep the extended option in false.

From your front js:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
$.ajax("/send", {
     data: { "strArr": fruits.join() },
     type: "POST",
     async: true,
 ......

From your server js:

router.post('/send', function(req, res) {
    var fruits = req.body.strArr.split(",");
    console.log(fruits); // This is an array
});
Semination answered 12/9, 2018 at 16:41 Comment(0)
C
1

You need to parse the second part of your object so that Node converts it from string to array.

JSON.parse(req.body.arrayOfObjects);

will return you the wanted array for the second part of your object

Calvano answered 14/11, 2018 at 11:34 Comment(0)
A
0

change extended option to true it will refrain from turning it to a json

Alienism answered 7/9, 2017 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.