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

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.

主站蜘蛛池模板: 涟水县| 山阴县| 肥城市| 昔阳县| 富阳市| 江山市| 颍上县| 遂平县| 荃湾区| 海淀区| 保亭| 仲巴县| 临桂县| 通河县| 延寿县| 阳谷县| 彰化市| 金华市| 美姑县| 平昌县| 革吉县| 万州区| 麻江县| 孟津县| 仁怀市| 和田县| 石林| 永安市| 庆云县| 含山县| 德阳市| 蒲江县| 汉川市| 禄劝| 辉县市| 祁连县| 慈利县| 英吉沙县| 屯昌县| 榆树市| 无棣县|