Node.js-使用querystring以GET/POST的形式发送和接收数组 [英] Node.js - Send and receive Array as GET/POST using querystring

查看:389
本文介绍了Node.js-使用querystring以GET/POST的形式发送和接收数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,但似乎不起作用:

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

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

我最终得到了5个子数组,它们对应于对象中的5个参数,但它们的名称中带有额外的'] ['字符:

{ array: 
   [ { '][param1': 'something' }
   , { '][param2': '123' }
   , { '][param2': 'something' }
   , { '][param4': '1234' }
   , { '][param1': 'hello' }
   ]
}

解决方案

有一个解决此问题的新节点程序包:"npm install qs".

https://github.com/ljharb/qs

用于支持嵌套的节点的查询字符串解析器,因为它已从0.3.x中删除,因此该库提供了以前的且通常需要的行为(并且速度是以前的两倍)"

如果任何人都可以告诉我为什么将其从0.3.x中删除,我将给您投票赞成您的评论. (我希望恢复对Node.js的信心.)

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

解决方案

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

这篇关于Node.js-使用querystring以GET/POST的形式发送和接收数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆