bravokiloecho
bravokiloecho

Reputation: 1463

How to parse data object in express from ajax POST

I'm posting to an express app using like this:

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

And this is what the data looks like:

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

When I log the req.body in the Express app, the results looks like this:

{
  '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>'
}

This means I am unable to access (eg) the border.top property using req.body.options.border.top.

What's going on here and how can I ensure that the object structure is maintained?

Many thanks!

Upvotes: 0

Views: 40

Answers (2)

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

First - How to retrieve POST query parameters in Express

Second, let's introduce some method for structure validation

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])
    }
  })
}

After that you can compare received object with the perfect one, like that;

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
}

Upvotes: 1

robertklep
robertklep

Reputation: 203359

You need to enable "extended syntax":

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

Upvotes: 1

Related Questions