cs04iz1
cs04iz1

Reputation: 1815

How to get POSTed (jquery) array data in Node.js (using express)

I am trying to post an array to my server. But I have difficulties in doing it properly.

The array I am trying to post, is an array of objects which is dynamically structured, thus I don't know it's length.

To be more precise, my array is of the form.

var names =[{id:1, name:"nick"},{id:2,name:"bob"},{id:3,name:"john"}.....{id:n, name:"whatever"}]

I am posting using jquery:

$.post("save_names", {
        'names[]': names
    }, function(results) {
        alert(results);
    }); 

My node code, is the following: (I use stormpath-express)

app.post('/save_names', config.access_group, function(req, res) {
    console.log("body ", req.body);
});

This way i am getting the following from the console.log

body  { 'names[]': [ '[object Object]', '[object Object]', '[object Object]' ] }

When i try to print the array : console.log("body ", req.body.names); I get body undefined

Can somebody explain why this is happening? How to solve my error, and why can't I just post names:names and simply work?

Upvotes: 3

Views: 5816

Answers (2)

sigod
sigod

Reputation: 6397

You're sending your data incorrectly. You can examine request in Development tools. You'll see something like this:

Form Data
    names[]:[object Object]
    names[]:[object Object]
    names[]:[object Object]
    names[]:[object Object]

Try converting data to JSON yourself:

$.post("save_names", {
        'names[]': JSON.stringify(names)
    }, function(results) {
        alert(results);
    });

Don't forget to correctly access your array: console.log("body ", req.body['names[]']);.

Upvotes: 4

vanadium23
vanadium23

Reputation: 3586

Yes, you req.body contains key names[], not names. So you can either grab from req.body['names[]'] or rewrite code to have name object:

$.post("save_names", {
        names: names
    }, function(results) {
        alert(results);
    }); 

And express code:

app.post('/alter_offer_sort', config.access_group, function(req, res) {
    console.log("body ", req.body.names);
});

P.S. probably you grab [] names from a GET Query. It's not how POST works.

UPDATE:

I also don't notice, that there is just string of object, so initialize bodyParser.

First install body-parser:

npm install --save body-parser

Then modify code to this:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Upvotes: 0

Related Questions