【问题标题】:How to parse data object in express from ajax POST如何从ajax POST中解析数据对象
【发布时间】:2016-09-21 10:39:38
【问题描述】:

我正在使用这样的方式发布到快速应用程序:

$.ajax
    type: "POST"
    url: localUrl
    data: data
    cache: false
    dataType: 'native'
    xhrFields:
        responseType: 'blob'

这就是data 的样子:

data =
    'options':
        'format': 'Letter'      
        'border':
            'top': '2in'
            'right': '1in'
            'bottom': '2in'
            'left': '1.5i'
        'header':
            'height': '45mm'
            'contents': header

当我在 Express 应用程序中记录 req.body 时,结果如下所示:

{
  'options[format]': 'Letter',
  'options[border][top]': '2in',
  'options[border][right]': '1in',
  'options[border][bottom]': '2in',
  'options[border][left]': '1.5i',
  'options[header][height]': '45mm',
  'options[header][contents]': '<div class="pdf-header">\n\tChart generated by http://collab.craft.dev\n</div>',
  'options[footer][height]': '28mm',
  'options[footer][contents]': '<div class="pdf-footer">\n\tTue May 24 2016 10:32:36 GMT+0100 (BST)\n</div>'
}

这意味着我无法使用req.body.options.border.top 访问(例如)border.top 属性。

这里发生了什么,如何确保对象结构得到维护?

非常感谢!

【问题讨论】:

  • req.body.options.border.top 不会工作?
  • 很遗憾没有。我认为是因为对象结构被折叠成我上面打印的格式。我意识到我打错了。现已编辑。

标签: json ajax post express


【解决方案1】:

首先 - How to retrieve POST query parameters in Express

其次,我们介绍一些结构验证的方法

function isValid(o, validStructure) {
  return Object.keys(validStructure).every(function(key) {
    if (Object.prototype.toString.call(validStructure[key]) === '[object Object]') {
      return isValid(o[key], validStructure[key])
    } else {
      return Object.prototype.toString.call(validStructure[key]) === Object.prototype.toString.call(o[key])
    }
  })
}

之后,您可以将收到的对象与完美的对象进行比较,就像这样;

var expetedStructure = {
  a: {},
  b: 'String',
  c: [],
  d: 1,
  e: {
    f: 'a'
  }
}

if(isValid(requestObj, expectedStructure)) {
  // suport it as requested object has valid structure
} else {
  // support validation error
}

【讨论】:

    【解决方案2】:

    您需要启用"extended syntax":

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

    【讨论】:

    • 完美,谢谢!通常设置为 false 有什么原因吗?
    • @bravokiloecho 文档指出默认值为 true。也许您使用的是旧版本?
    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 2016-08-02
    • 2019-12-05
    • 2011-07-23
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多