【问题标题】:express4 bodyparser post array item is udefinedexpress bodyparser 后数组项未定义
【发布时间】:2016-05-18 03:34:39
【问题描述】:

我有一个快速应用程序,它使用 bodyParser 从发布请求中获取 json 内容。如果我写出整个正文的内容,它看起来像这样:

{
  'device[group]': 'TESTGROUP',
  'device[name]': 'TESTNAME',
  'events[http][address]': 'http://192.168.77.11/api'
}

在我写出给我不确定的事件内容之后。我做错了什么?

我的代码如下:

app.post('/settings', function(req, res) {
    console.log(req.body);
    console.log(req.body.events); // undefined

客户端代码:

$.ajax({
            url: postURL,
            data: {
                    "device": {
                        "group": $('#devicegroup').val(),
                        "name": $('#devicename').val()
                    },
                    "events": {
                        "http": {
                            "address": $('#httpaddress').val()
                        }
                    }
            },
            type: 'POST',
            dataType: 'json'
        }).success(function(response) {
            console.log(response);
        });

【问题讨论】:

  • 这样试试,因为 events 是一个二维数组 console.log(req.body.events[http][address]);
  • 是否安装了bodyparser 依赖项?如果没有,请先运行$npm install bodyparser --save

标签: jquery ajax node.js express body-parser


【解决方案1】:

您需要以String 发送数据,而不是PlainObject

$.ajax({
            url: postURL,
            data: JSON.stringify( {
                    "device": {
                        "group": $('#devicegroup').val(),
                        "name": $('#devicename').val()
                    },
                    "events": {
                        "http": {
                            "address": $('#httpaddress').val()
                        }
                    }
            } ),
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json'
        }).success(function(response) {
            console.log(response);
        });

【讨论】:

  • 我想我必须在这之后在服务器上使用 JSON.parse(req.body) ,对吧?不幸的是,我有来自 json 解析器的神秘异常,例如“意外令牌:u”似乎该字符串不包含格式良好的 json 字符串。
  • @Perrier 不,您只需将contentType 设置为application/json(请参阅更新)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
  • 2018-09-16
  • 2019-08-21
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多