- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 241字
- 2021-07-02 19:28:50
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.
- RCNP實驗指南:構建高級的路由互聯網絡(BARI)
- 高校網絡道德教育研究
- SOA用戶指南
- Hands-On Chatbot Development with Alexa Skills and Amazon Lex
- 網絡創新指數研究
- HCNA網絡技術
- 物聯網信息安全
- Yii Application Development Cookbook(Second Edition)
- 網絡基礎與網絡管理項目化教程
- Windows Server 2012 Hyper-V虛擬化管理實踐
- React Cookbook
- 紅藍攻防:構建實戰化網絡安全防御體系
- bash網絡安全運維
- 世界網力:2018年中國網信產業桔皮書
- 互聯網下一站:5G與AR/VR的融合