Javascript / Json:对象的对象转换为关联数组

时间:2015-10-13 17:09:38

标签: javascript json angularjs node.js express

使用AngularJS,我将以下数据发送到我的API:

$http.post('/api/test', { credits: { value:"100", action:"test" } });

在我的nodeJS(+ Express)后端,我得到以下数据:

enter image description here

为什么我的帖子数据已转换为关联数组?

我想要的是:

credits : Object
      action : "test"
      velue  : "100"

1 个答案:

答案 0 :(得分:3)

使用body-parser包,选项"扩展"同样如此,

app.use(bodyParser.urlencoded({ extended: true }));

示例:

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(){

});

导致控制台

{ credits: { value: '100', action: 'test' } }
{ value: '100', action: 'test' }
100
test
value -> 100
action -> test