0

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!

2
  • req.body.options.border.top will not work? Commented May 24, 2016 at 9:44
  • Unfortunately not. I think because the object structure is being collapsed into the format I printed above. I realised I'd typed it out wrong. Now edited. Commented May 24, 2016 at 9:47

2 Answers 2

1

You need to enable "extended syntax":

app.use( bodyParser.urlencoded({ extended : true }) );
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thank you! Is there a reason why that's usually set to false?
@bravokiloecho the documentation states that the default is true. Perhaps you're using an older version?
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.