May 10, 2021 Node.js
This section introduces you to .js Query Strings.
稳定性: 3 - 稳定
The Node .js module provides tools for handling qury strings, which you can access by:
const querystring = require('querystring');
Node.js Query Strings contains the following methods:
This method serializes an object into a qury string.
You can choose to override the default separator
'&'
and the assignor
'='
The Options object may contain
encodeURIComponent
(default:
querystring.escape
can encode
non-utf8
needed.
Example:
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
// returns
'foo=bar&baz=qux&baz=quux&corge='
querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
// returns
'foo:bar;baz:qux'
// Suppose gbkEncodeURIComponent function already exists,
// it can encode string with `gbk` encoding
querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
{ encodeURIComponent: gbkEncodeURIComponent })
// returns
'w=%D6%D0%CE%C4&foo=bar'
This method can be used to reseries the qury string into an object.
You can choose to override the default separator
'&'
and the assignor
'='
Options objects may
maxKeys
(default: 1000) to limit processed health values (keys).
If set to 0, you can remove the limit on the number of key values.
Options objects may contain
decodeURIComponent
property (default:
querystring.unescape
that can be used to
non-utf8
if needed.
Example:
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
// Suppose gbkDecodeURIComponent function already exists,
// it can decode `gbk` encoding string
querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
{ decodeURIComponent: gbkDecodeURIComponent })
// returns
{ w: '中文', foo: 'bar' }
The escape function is
querystring.stringify
and can be rewritten if necessary.
The unescape function is
querystring.parse
If necessary, you can override it.
First try to use
decodeURIComponent
and if it fails, it rolls back and doesn't throw incorrectly formatted URLs.