第29节 Node.js Query Strings

本节为你介绍Node.js Query Strings。

复制代码
稳定性: 3 - 稳定

该Node.js模块提供了一些处理query strings的工具,你可以通过以下方式访问它:

复制代码
const querystring = require('querystring');

Node.js Query Strings包含的方法如下:

querystring.stringify(obj[, sep][, eq][, options])

该方法可以将一个对象序列化化为一个query string 。

可以选择重写默认的分隔符('&') 和分配符 ('=')。

Options对象可能包含encodeURIComponent属性 (默认:querystring.escape),如果需要,它可以用non-utf8编码字符串。

例子:

复制代码
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'

querystring.parse(str[, sep][, eq][, options])

该方法可以将query string反序列化为对象。

你可以选择重写默认的分隔符('&') 和分配符 ('=')。

Options对象可能包含maxKeys属性(默认:1000),用来限制处理过的健值(keys)。设置为0的话,可以去掉键值的数量限制。

Options 对象可能包含decodeURIComponent属性(默认:querystring.unescape),如果需要,可以用来解码non-utf8编码的字符串。

例子:

复制代码
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' }

querystring.escape

escape函数供querystring.stringify使用,必要时,可以重写。

querystring.unescape

unescape函数供querystring.parse使用。必要时,可以重写。

首先会尝试用decodeURIComponent,如果失败,会回退,不会抛出格式不正确的URLs。

相关推荐
网络点点滴15 小时前
NPM的包版本管理
前端·npm·node.js
Allen正心正念202515 小时前
前端——Node.js&npm,学点前端的东西
前端·npm·node.js
fqbqrr16 小时前
2604,vim可定制对话框
vim
. . . . .17 小时前
Node.js 模块系统
node.js
我叫汪枫1 天前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
技术钱1 天前
nodejs使用RustFS容器服务搭建对象存储oss
node.js·egg
大貔貅喝啤酒1 天前
接口测试_Postman(详细版)
javascript·测试工具·node.js·自动化·postman
桜吹雪1 天前
Langchain.js官方文档:构建具备按需加载技能的 SQL 助手
javascript·人工智能·node.js
一袋米扛几楼981 天前
【报错问题】解决 Vercel 部署报错:Express 类型失效与 TypeScript 2349/2339/2769 错误排查
ubuntu·typescript·express
拾贰_C2 天前
【node.js | Ubuntu | update】如何升级旧的nodejs本版至最新;如何升级npm
ubuntu·npm·node.js