Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Send and receive Array as GET/POST using querystring

I've got the following code, but it doesn't seem to work:

var post_req = {
    array: [
        [ {
            param1: 'something',
            param2: 123
        } ],
        [ ],
        [ ],
        [ {
            param2: 'something',
            param4: 1234,
            param1: 'hello'
        } ]
    ]
};
var data_send = querystring.stringify(post_req);

var request = client.request('POST', '/', headers);
request.end(data_send);

and

if( req.method == 'POST' ) {
    req.addListener('data', function(chunk)
    {
        POST = querystring.parse(chunk);
        console.log(POST);
    }
}

I end up with 5 sub-arrays, corresponding to the 5 parameters in the objects but with extra '][' characters in their names:

{ array: 
   [ { '][param1': 'something' }
   , { '][param2': '123' }
   , { '][param2': 'something' }
   , { '][param4': '1234' }
   , { '][param1': 'hello' }
   ]
}
like image 422
Vanwaril Avatar asked Jan 03 '11 17:01

Vanwaril


2 Answers

There is a new node package that fixes this: "npm install qs".

https://github.com/ljharb/qs

"query string parser for node supporting nesting, as it was removed from 0.3.x, so this library provides the previous and commonly desired behaviour (and twice as fast)"

If anyone can tell me why it was removed from 0.3.x, I will give you an upvote for your comment. (I want my confidence in Node.js restored.)

like image 64
OCDev Avatar answered Sep 18 '22 22:09

OCDev


To confirm my comment above, node's querystring.stringify function won't handle nested arrays (at the time of writing).

You can see the source of stringify at https://github.com/ry/node/blob/master/lib/querystring.js

Note that it handles one level of arrays but it doesn't recurse. When it finds an array it uses stringifyPrimitive to encode the array's values. You can see that stringifyPrimitive doesn't handle arrays, only number, boolean and string.

As I suggested in my comment, given that you're using a POST request a better idea would be to use JSON encoding for your complex data structure.

Or use https://github.com/visionmedia/node-querystring as suggested by @FriendlyDev

like image 45
RandomEtc Avatar answered Sep 19 '22 22:09

RandomEtc