import Qs from 'qs' 学习笔记

 https://www.npmjs.com/package/qs

Usage

 
  
var qs = require('qs');
var assert = require('assert');
 
var obj = qs.parse('a=c');
assert.deepEqual(obj, { a: 'c' });
 
var str = qs.stringify(obj);
assert.equal(str, 'a=c');

Parsing Objects

 
  
qs.parse(string, [options]);

qs allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets []. For example, the string 'foo[bar]=baz' converts to:

 
  
assert.deepEqual(qs.parse('foo[bar]=baz'), {
    foo: {
        bar: 'baz'
    }
});

Parsing Arrays

qs can also parse arrays using a similar [] notation:

 
 
var withArray = qs.parse('a[]=b&a[]=c');
assert.deepEqual(withArray, { a: ['b', 'c'] });

Stringifying

 
  
qs.stringify(object, [options]);

When stringifying, qs by default URI encodes output. Objects are stringified as you would expect:

 
  
assert.equal(qs.stringify({ a: 'b' }), 'a=b');
assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');

This encoding can be disabled by setting the encode option to false:

 
  
var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
assert.equal(unencoded, 'a[b]=c');

Handling of null values

By default, null values are treated like empty strings:

 
  
var withNull = qs.stringify({ a: null, b: '' });
assert.equal(withNull, 'a=&b=');

Dealing with special character sets

By default the encoding and decoding of characters is done in utf-8. If you wish to encode querystrings to a different character set (i.e. Shift JIS) you can use the qs-iconv library:

 
  
var encoder = require('qs-iconv/encoder')('shift_jis');
var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder });
assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I');

RFC 3986 and RFC 1738 space encoding

RFC3986 used as default option and encodes ' ' to %20 which is backward compatible. In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'.

assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c');
assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c');


猜你喜欢

转载自blog.csdn.net/zgpeterliu/article/details/80111116
qs
今日推荐