Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Json : Object of object converted to associative array

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 :

enter image description here

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"
like image 873
IggY Avatar asked Dec 27 '25 18:12

IggY


1 Answers

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
like image 177
davcs86 Avatar answered Dec 30 '25 10:12

davcs86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!