tj / node-querystring

querystring parser for node and the browser - supporting nesting (used by Express, Connect, etc)
MIT License
455 stars 66 forks source link

How to use with req.body? #42

Closed cyberwombat closed 12 years ago

cyberwombat commented 12 years ago

Hi - trying to figure out how to parse square bracket notation in a form (user[1][name]...) but can't seem to get this going in Express3. I just get junk. Tried passing req.body to qs.parse but that did nothing and I am not finding docs on this.

To give an idea of what I get....

My form looks a bit like this (non necessary html removed):

<input name="title" value="My title"/>
<input name="variant[0][name]" value="color"/>
<input name="variant[0][entries][0][label]" value="red"/>
<input name="variant[0][entries][0][price]" value="2"/>
<input name="variant[0][entries][1][label]" value="blue"/>
<input name="variant[0][entries][1][price]" value="3"/>

Then I do:

var qs = require('qs');
var body = qs.parse(req.body);
console.log(body);

Console output:

{ 
title: 'My title',
variant: 
 [ ,
   ,
   ,
   ,
   ,
  (there are approx 850 of these commas)
   ,
   ,
   { name: 'color', entries: [Object] } ] 
}

If I console.log(req.body):

title: 'My title',
'variant[0][name]': 'color',
'variant[0][entries][0][label]': 'red',
'variant[0][entries][0][price]': '2',
'variant[0][entries][1][label]': 'blue',
'variant[0][entries][1][price]': '2'
}

Thanks for your time

tj commented 12 years ago

use bodyParser() it does this for you already

cyberwombat commented 12 years ago

I use bodyParser - the result of that is:

title: 'My title',
'variant[0][name]': 'color',
'variant[0][entries][0][label]': 'red',
'variant[0][entries][0][price]': '2',
'variant[0][entries][1][label]': 'blue',
'variant[0][entries][1][price]': '2'
}

Though perhaps I am missing a step - I would assume that it would automatically parse my POST request into req.body. How can I test that it is working correctly?

I have this in my app.js app.use(express.bodyParser());

cyberwombat commented 12 years ago

Ok - the issue is with the serialization of my form into JSON. I made the mistake of using serializeArray which doesn't handle nesting. Evidently there is not really a solution that I can find as most attempts to deal with this are broken or non working but I will keep searching.