bravokiloecho bravokiloecho - 6 months ago 13
JSON Question

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!

Answer

You need to enable "extended syntax":

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