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, thu
Solution 1:
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[]']);
.
Solution 2:
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())
Post a Comment for "How To Get POSTed (jquery) Array Data In Node.js (using Express)"