With AngularJS, I send the following data to my API :
$http.post('/api/test', { credits: { value:"100", action:"test" } });
In my nodeJS (+Express) backend, I get the following data :

Why does my post data have been converted to an associative array ?
What i'd like to have instead is :
credits : Object
action : "test"
velue : "100"
Using the body-parser package, with the option "extended" as true,
app.use(bodyParser.urlencoded({ extended: true }));
Example:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/test',function (req, res) {
var data = req.body;
console.log(data);
console.log(data.credits);
console.log(data.credits.value);
console.log(data.credits.action);
var result = "";
for (var key in data.credits) {
if (data.credits.hasOwnProperty(key)) {
console.log(key + " -> " + data.credits[key]);
result += key + " -> " + data.credits[key];
}
}
res.send(result);
res.end();
});
app.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
});
results in console
{ credits: { value: '100', action: 'test' } }
{ value: '100', action: 'test' }
100
test
value -> 100
action -> test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With