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

2019-02-12 04:48发布

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

3条回答
SAY GOODBYE
2楼-- · 2019-02-12 05:09

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-12 05:11

Don't use querystring.parse for recreating a JSON object sent as string. Use instead JSON.parse. And use JSON.stringify instead of querystring.stringify

querystring is useful when you send parameter encoded in the url or when you post a form. But there is no point in using it if you send just one JSON object with all your data.

In your scenario I would dismiss the querystring library and use JSON library, which is already included. It would be cleaner and faster.

http://www.json.org/js.html

查看更多
家丑人穷心不美
4楼-- · 2019-02-12 05:24

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.)

查看更多
登录 后发表回答