官术网_书友最值得收藏!

The Querystring module

As we saw with the URL module, query strings often need to be parsed into a map of key/value pairs. The Querystring module will either decompose an existing query string into its parts, or assemble a query string from a map of key/value pairs.

For example, querystring.parse("foo=bar&bingo=bango") will return:

{
foo: 'bar',
bingo: 'bango'
}

If our query strings are not formatted using the normal "&" separator and "=" assignment character, the Querystring module offers customizable parsing.

The second argument to Querystring can be a custom separator string, and the third, a custom assignment string. For example, the following will return the same mapping as given previously on a query string with custom formatting:

let qs = require("querystring");
console.log(qs.parse("foo:bar^bingo:bango", "^", ":"));
// { foo: 'bar', bingo: 'bango' }

You can compose a query string using the Querystring.stringify method:

console.log(qs.stringify({ foo: 'bar', bingo: 'bango' }));
// foo=bar&bingo=bango

As with parse, stringify also accepts custom separator and assignment arguments:

console.log(qs.stringify({ foo: 'bar', bingo: 'bango' }, "^", ":"));
// foo:bar^bingo:bango

Query strings are commonly associated with GET requests, seen following the ? character. As we saw previously, in these cases, automatic parsing of these strings using the url module is the most straightforward solution. However, strings formatted in such a manner also show up when we're handling POST data, and in these cases, the Querystring module is of real use. We'll discuss this usage shortly, but first, something about HTTP headers.

主站蜘蛛池模板: 临沧市| 介休市| 长寿区| 九寨沟县| 霍林郭勒市| 荥阳市| 伊通| 奉节县| 新密市| 江城| 甘德县| 闽清县| 深水埗区| 绵竹市| 栾川县| 禹州市| 东山县| 永靖县| 民乐县| 山东省| 桂平市| 洪雅县| 偃师市| 万荣县| 板桥市| 天津市| 新竹市| 曲水县| 绥江县| 上栗县| 攀枝花市| 绍兴市| 云浮市| 维西| 西华县| 海兴县| 天津市| 泾川县| 邵阳市| 宜阳县| 黑龙江省|