【问题标题】:Javascript/Json : Object of object converted to associative arrayJavascript/Json:对象的对象转换为关联数组
【发布时间】:2016-01-11 13:18:13
【问题描述】:

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

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

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

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

我想要的是:

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

【问题讨论】:

  • 我建议使用 body-parser,npmjs.com/package/body-parser
  • 你用的是快递吗?
  • 是的,我使用的是 express,抱歉没有提及。
  • 文档中有一个例子expressjs.com/api.html#req.body
  • @davcs86 :这是否意味着我没有做任何“错误”,这是本机正文解析器的奇怪行为?

标签: javascript json angularjs node.js express


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    相关资源
    最近更新 更多