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

こ雲淡風輕ζ 提交于 2019-11-30 18:28:45
OCDev

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!