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

后端 未结 3 583
太阳男子
太阳男子 2021-01-04 07:39

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

var post_req = {
    array: [
        [ {
            param1: \'something\',
            param2:          


        
相关标签:
3条回答
  • 2021-01-04 08:04

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

    0 讨论(0)
  • 2021-01-04 08: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

    0 讨论(0)
  • 2021-01-04 08:13

    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

    0 讨论(0)
提交回复
热议问题