You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

570 lines
18 KiB

4 years ago
  1. # qs <sup>[![Version Badge][2]][1]</sup>
  2. [![Build Status][3]][4]
  3. [![dependency status][5]][6]
  4. [![dev dependency status][7]][8]
  5. [![License][license-image]][license-url]
  6. [![Downloads][downloads-image]][downloads-url]
  7. [![npm badge][11]][1]
  8. A querystring parsing and stringifying library with some added security.
  9. Lead Maintainer: [Jordan Harband](https://github.com/ljharb)
  10. The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).
  11. ## Usage
  12. ```javascript
  13. var qs = require('qs');
  14. var assert = require('assert');
  15. var obj = qs.parse('a=c');
  16. assert.deepEqual(obj, { a: 'c' });
  17. var str = qs.stringify(obj);
  18. assert.equal(str, 'a=c');
  19. ```
  20. ### Parsing Objects
  21. [](#preventEval)
  22. ```javascript
  23. qs.parse(string, [options]);
  24. ```
  25. **qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.
  26. For example, the string `'foo[bar]=baz'` converts to:
  27. ```javascript
  28. assert.deepEqual(qs.parse('foo[bar]=baz'), {
  29. foo: {
  30. bar: 'baz'
  31. }
  32. });
  33. ```
  34. When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like:
  35. ```javascript
  36. var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true });
  37. assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } });
  38. ```
  39. By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.
  40. ```javascript
  41. var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });
  42. assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });
  43. ```
  44. URI encoded strings work too:
  45. ```javascript
  46. assert.deepEqual(qs.parse('a%5Bb%5D=c'), {
  47. a: { b: 'c' }
  48. });
  49. ```
  50. You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`:
  51. ```javascript
  52. assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), {
  53. foo: {
  54. bar: {
  55. baz: 'foobarbaz'
  56. }
  57. }
  58. });
  59. ```
  60. By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like
  61. `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be:
  62. ```javascript
  63. var expected = {
  64. a: {
  65. b: {
  66. c: {
  67. d: {
  68. e: {
  69. f: {
  70. '[g][h][i]': 'j'
  71. }
  72. }
  73. }
  74. }
  75. }
  76. }
  77. };
  78. var string = 'a[b][c][d][e][f][g][h][i]=j';
  79. assert.deepEqual(qs.parse(string), expected);
  80. ```
  81. This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`:
  82. ```javascript
  83. var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
  84. assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });
  85. ```
  86. The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number.
  87. For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option:
  88. ```javascript
  89. var limited = qs.parse('a=b&c=d', { parameterLimit: 1 });
  90. assert.deepEqual(limited, { a: 'b' });
  91. ```
  92. To bypass the leading question mark, use `ignoreQueryPrefix`:
  93. ```javascript
  94. var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true });
  95. assert.deepEqual(prefixed, { a: 'b', c: 'd' });
  96. ```
  97. An optional delimiter can also be passed:
  98. ```javascript
  99. var delimited = qs.parse('a=b;c=d', { delimiter: ';' });
  100. assert.deepEqual(delimited, { a: 'b', c: 'd' });
  101. ```
  102. Delimiters can be a regular expression too:
  103. ```javascript
  104. var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });
  105. assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' });
  106. ```
  107. Option `allowDots` can be used to enable dot notation:
  108. ```javascript
  109. var withDots = qs.parse('a.b=c', { allowDots: true });
  110. assert.deepEqual(withDots, { a: { b: 'c' } });
  111. ```
  112. If you have to deal with legacy browsers or services, there's
  113. also support for decoding percent-encoded octets as iso-8859-1:
  114. ```javascript
  115. var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' });
  116. assert.deepEqual(oldCharset, { a: '§' });
  117. ```
  118. Some services add an initial `utf8=✓` value to forms so that old
  119. Internet Explorer versions are more likely to submit the form as
  120. utf-8. Additionally, the server can check the value against wrong
  121. encodings of the checkmark character and detect that a query string
  122. or `application/x-www-form-urlencoded` body was *not* sent as
  123. utf-8, eg. if the form had an `accept-charset` parameter or the
  124. containing page had a different character set.
  125. **qs** supports this mechanism via the `charsetSentinel` option.
  126. If specified, the `utf8` parameter will be omitted from the
  127. returned object. It will be used to switch to `iso-8859-1`/`utf-8`
  128. mode depending on how the checkmark is encoded.
  129. **Important**: When you specify both the `charset` option and the
  130. `charsetSentinel` option, the `charset` will be overridden when
  131. the request contains a `utf8` parameter from which the actual
  132. charset can be deduced. In that sense the `charset` will behave
  133. as the default charset rather than the authoritative charset.
  134. ```javascript
  135. var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', {
  136. charset: 'iso-8859-1',
  137. charsetSentinel: true
  138. });
  139. assert.deepEqual(detectedAsUtf8, { a: 'ø' });
  140. // Browsers encode the checkmark as &#10003; when submitting as iso-8859-1:
  141. var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', {
  142. charset: 'utf-8',
  143. charsetSentinel: true
  144. });
  145. assert.deepEqual(detectedAsIso8859_1, { a: 'ø' });
  146. ```
  147. If you want to decode the `&#...;` syntax to the actual character,
  148. you can specify the `interpretNumericEntities` option as well:
  149. ```javascript
  150. var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', {
  151. charset: 'iso-8859-1',
  152. interpretNumericEntities: true
  153. });
  154. assert.deepEqual(detectedAsIso8859_1, { a: '☺' });
  155. ```
  156. It also works when the charset has been detected in `charsetSentinel`
  157. mode.
  158. ### Parsing Arrays
  159. **qs** can also parse arrays using a similar `[]` notation:
  160. ```javascript
  161. var withArray = qs.parse('a[]=b&a[]=c');
  162. assert.deepEqual(withArray, { a: ['b', 'c'] });
  163. ```
  164. You may specify an index as well:
  165. ```javascript
  166. var withIndexes = qs.parse('a[1]=c&a[0]=b');
  167. assert.deepEqual(withIndexes, { a: ['b', 'c'] });
  168. ```
  169. Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number
  170. to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving
  171. their order:
  172. ```javascript
  173. var noSparse = qs.parse('a[1]=b&a[15]=c');
  174. assert.deepEqual(noSparse, { a: ['b', 'c'] });
  175. ```
  176. Note that an empty string is also a value, and will be preserved:
  177. ```javascript
  178. var withEmptyString = qs.parse('a[]=&a[]=b');
  179. assert.deepEqual(withEmptyString, { a: ['', 'b'] });
  180. var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c');
  181. assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] });
  182. ```
  183. **qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will
  184. instead be converted to an object with the index as the key. This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array.
  185. ```javascript
  186. var withMaxIndex = qs.parse('a[100]=b');
  187. assert.deepEqual(withMaxIndex, { a: { '100': 'b' } });
  188. ```
  189. This limit can be overridden by passing an `arrayLimit` option:
  190. ```javascript
  191. var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 });
  192. assert.deepEqual(withArrayLimit, { a: { '1': 'b' } });
  193. ```
  194. To disable array parsing entirely, set `parseArrays` to `false`.
  195. ```javascript
  196. var noParsingArrays = qs.parse('a[]=b', { parseArrays: false });
  197. assert.deepEqual(noParsingArrays, { a: { '0': 'b' } });
  198. ```
  199. If you mix notations, **qs** will merge the two items into an object:
  200. ```javascript
  201. var mixedNotation = qs.parse('a[0]=b&a[b]=c');
  202. assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } });
  203. ```
  204. You can also create arrays of objects:
  205. ```javascript
  206. var arraysOfObjects = qs.parse('a[][b]=c');
  207. assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] });
  208. ```
  209. Some people use comma to join array, **qs** can parse it:
  210. ```javascript
  211. var arraysOfObjects = qs.parse('a=b,c', { comma: true })
  212. assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] })
  213. ```
  214. (_this cannot convert nested objects, such as `a={b:1},{c:d}`_)
  215. ### Stringifying
  216. [](#preventEval)
  217. ```javascript
  218. qs.stringify(object, [options]);
  219. ```
  220. When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect:
  221. ```javascript
  222. assert.equal(qs.stringify({ a: 'b' }), 'a=b');
  223. assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
  224. ```
  225. This encoding can be disabled by setting the `encode` option to `false`:
  226. ```javascript
  227. var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
  228. assert.equal(unencoded, 'a[b]=c');
  229. ```
  230. Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`:
  231. ```javascript
  232. var encodedValues = qs.stringify(
  233. { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] },
  234. { encodeValuesOnly: true }
  235. );
  236. assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h');
  237. ```
  238. This encoding can also be replaced by a custom encoding method set as `encoder` option:
  239. ```javascript
  240. var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) {
  241. // Passed in values `a`, `b`, `c`
  242. return // Return encoded string
  243. }})
  244. ```
  245. _(Note: the `encoder` option does not apply if `encode` is `false`)_
  246. Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values:
  247. ```javascript
  248. var decoded = qs.parse('x=z', { decoder: function (str) {
  249. // Passed in values `x`, `z`
  250. return // Return decoded string
  251. }})
  252. ```
  253. Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage.
  254. When arrays are stringified, by default they are given explicit indices:
  255. ```javascript
  256. qs.stringify({ a: ['b', 'c', 'd'] });
  257. // 'a[0]=b&a[1]=c&a[2]=d'
  258. ```
  259. You may override this by setting the `indices` option to `false`:
  260. ```javascript
  261. qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
  262. // 'a=b&a=c&a=d'
  263. ```
  264. You may use the `arrayFormat` option to specify the format of the output array:
  265. ```javascript
  266. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
  267. // 'a[0]=b&a[1]=c'
  268. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
  269. // 'a[]=b&a[]=c'
  270. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
  271. // 'a=b&a=c'
  272. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' })
  273. // 'a=b,c'
  274. ```
  275. When objects are stringified, by default they use bracket notation:
  276. ```javascript
  277. qs.stringify({ a: { b: { c: 'd', e: 'f' } } });
  278. // 'a[b][c]=d&a[b][e]=f'
  279. ```
  280. You may override this to use dot notation by setting the `allowDots` option to `true`:
  281. ```javascript
  282. qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true });
  283. // 'a.b.c=d&a.b.e=f'
  284. ```
  285. Empty strings and null values will omit the value, but the equals sign (=) remains in place:
  286. ```javascript
  287. assert.equal(qs.stringify({ a: '' }), 'a=');
  288. ```
  289. Key with no values (such as an empty object or array) will return nothing:
  290. ```javascript
  291. assert.equal(qs.stringify({ a: [] }), '');
  292. assert.equal(qs.stringify({ a: {} }), '');
  293. assert.equal(qs.stringify({ a: [{}] }), '');
  294. assert.equal(qs.stringify({ a: { b: []} }), '');
  295. assert.equal(qs.stringify({ a: { b: {}} }), '');
  296. ```
  297. Properties that are set to `undefined` will be omitted entirely:
  298. ```javascript
  299. assert.equal(qs.stringify({ a: null, b: undefined }), 'a=');
  300. ```
  301. The query string may optionally be prepended with a question mark:
  302. ```javascript
  303. assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d');
  304. ```
  305. The delimiter may be overridden with stringify as well:
  306. ```javascript
  307. assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
  308. ```
  309. If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option:
  310. ```javascript
  311. var date = new Date(7);
  312. assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A'));
  313. assert.equal(
  314. qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }),
  315. 'a=7'
  316. );
  317. ```
  318. You may use the `sort` option to affect the order of parameter keys:
  319. ```javascript
  320. function alphabeticalSort(a, b) {
  321. return a.localeCompare(b);
  322. }
  323. assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y');
  324. ```
  325. Finally, you can use the `filter` option to restrict which keys will be included in the stringified output.
  326. If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you
  327. pass an array, it will be used to select properties and array indices for stringification:
  328. ```javascript
  329. function filterFunc(prefix, value) {
  330. if (prefix == 'b') {
  331. // Return an `undefined` value to omit a property.
  332. return;
  333. }
  334. if (prefix == 'e[f]') {
  335. return value.getTime();
  336. }
  337. if (prefix == 'e[g][0]') {
  338. return value * 2;
  339. }
  340. return value;
  341. }
  342. qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc });
  343. // 'a=b&c=d&e[f]=123&e[g][0]=4'
  344. qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] });
  345. // 'a=b&e=f'
  346. qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] });
  347. // 'a[0]=b&a[2]=d'
  348. ```
  349. ### Handling of `null` values
  350. By default, `null` values are treated like empty strings:
  351. ```javascript
  352. var withNull = qs.stringify({ a: null, b: '' });
  353. assert.equal(withNull, 'a=&b=');
  354. ```
  355. Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings.
  356. ```javascript
  357. var equalsInsensitive = qs.parse('a&b=');
  358. assert.deepEqual(equalsInsensitive, { a: '', b: '' });
  359. ```
  360. To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null`
  361. values have no `=` sign:
  362. ```javascript
  363. var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
  364. assert.equal(strictNull, 'a&b=');
  365. ```
  366. To parse values without `=` back to `null` use the `strictNullHandling` flag:
  367. ```javascript
  368. var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true });
  369. assert.deepEqual(parsedStrictNull, { a: null, b: '' });
  370. ```
  371. To completely skip rendering keys with `null` values, use the `skipNulls` flag:
  372. ```javascript
  373. var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true });
  374. assert.equal(nullsSkipped, 'a=b');
  375. ```
  376. If you're communicating with legacy systems, you can switch to `iso-8859-1`
  377. using the `charset` option:
  378. ```javascript
  379. var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' });
  380. assert.equal(iso, '%E6=%E6');
  381. ```
  382. Characters that don't exist in `iso-8859-1` will be converted to numeric
  383. entities, similar to what browsers do:
  384. ```javascript
  385. var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' });
  386. assert.equal(numeric, 'a=%26%239786%3B');
  387. ```
  388. You can use the `charsetSentinel` option to announce the character by
  389. including an `utf8=✓` parameter with the proper encoding if the checkmark,
  390. similar to what Ruby on Rails and others do when submitting forms.
  391. ```javascript
  392. var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true });
  393. assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA');
  394. var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' });
  395. assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6');
  396. ```
  397. ### Dealing with special character sets
  398. By default the encoding and decoding of characters is done in `utf-8`,
  399. and `iso-8859-1` support is also built in via the `charset` parameter.
  400. If you wish to encode querystrings to a different character set (i.e.
  401. [Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the
  402. [`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library:
  403. ```javascript
  404. var encoder = require('qs-iconv/encoder')('shift_jis');
  405. var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder });
  406. assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I');
  407. ```
  408. This also works for decoding of query strings:
  409. ```javascript
  410. var decoder = require('qs-iconv/decoder')('shift_jis');
  411. var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder });
  412. assert.deepEqual(obj, { a: 'こんにちは!' });
  413. ```
  414. ### RFC 3986 and RFC 1738 space encoding
  415. RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible.
  416. In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'.
  417. ```
  418. assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
  419. assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c');
  420. assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c');
  421. ```
  422. [1]: https://npmjs.org/package/qs
  423. [2]: http://versionbadg.es/ljharb/qs.svg
  424. [3]: https://api.travis-ci.org/ljharb/qs.svg
  425. [4]: https://travis-ci.org/ljharb/qs
  426. [5]: https://david-dm.org/ljharb/qs.svg
  427. [6]: https://david-dm.org/ljharb/qs
  428. [7]: https://david-dm.org/ljharb/qs/dev-status.svg
  429. [8]: https://david-dm.org/ljharb/qs?type=dev
  430. [9]: https://ci.testling.com/ljharb/qs.png
  431. [10]: https://ci.testling.com/ljharb/qs
  432. [11]: https://nodei.co/npm/qs.png?downloads=true&stars=true
  433. [license-image]: http://img.shields.io/npm/l/qs.svg
  434. [license-url]: LICENSE
  435. [downloads-image]: http://img.shields.io/npm/dm/qs.svg
  436. [downloads-url]: http://npm-stat.com/charts.html?package=qs