How to get POSTed (jquery) array data in Node.js (using express)
I am trying to send an array to my server. But I have difficulty with this.
The array I'm trying to post is an array of objects that is dynamically structured, so I don't know its length.
To be more precise, my array is shaped.
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 as follows: (I am using stormpath-express)
app.post('/save_names', config.access_group, function(req, res) {
console.log("body ", req.body);
});
So I get the following from console.log
body { 'names[]': [ '[object Object]', '[object Object]', '[object Object]' ] }
When I try to print the array: console.log("body ", req.body.names);
I getbody undefined
Can someone explain why this is happening? How to solve my mistake and why can't I just post names: names and just work?
source to share
You are sending your details incorrectly. You can check the request in development tools. You will see something like this:
Form Data
names[]:[object Object]
names[]:[object Object]
names[]:[object Object]
names[]:[object Object]
Try converting the data to JSON yourself:
$.post("save_names", {
'names[]': JSON.stringify(names)
}, function(results) {
alert(results);
});
Do not forget to access your array: console.log("body ", req.body['names[]']);
.
source to share
Yes, you req.body
contain the key names[]
, not names
. So you can either go from req.body['names[]']
or rewrite your code to have a name object:
$.post("save_names", {
names: names
}, function(results) {
alert(results);
});
And to express the code:
app.post('/alter_offer_sort', config.access_group, function(req, res) {
console.log("body ", req.body.names);
});
PS you are probably taking names []
from the GET request. This is not how POST works.
UPDATE
I also don't notice that there is only an object string, so initialize the bodyParser.
First install body-parser:
npm install --save body-parser
Then change the code:
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())
source to share