本文共 1920 字,大约阅读时间需要 6 分钟。
作为 Node.js 核内模块,url 模块和 querystring 模块 提供了对 URL 和查询字符串 的处理工具,显著提升了在开发过程中的 URL 解析与处理能力。
url 模块 提供了对 URL 的结构化解析,便于提取各组成部分。其主要功能包括 URL 解析、各部分属性获取、重建 URL 等。
querystring 模块 专门处理 URL 查询字符串的解析与格式化,能够根据特定格式将对象转换为查询字符串,或将查询字符串转换为易于处理的对象格式。
new URL(input[, base])
通过将 input 解析到 base 上创建 URL 对象,input 可以是完整的 URL 字符串,或是 URL 的部分组成部分。
href
获取或设置整个 URLprotocol
获取或设置 协议部分hostname
获取或设置 主机名port
获取或设置 端口部分host
获取或设置 主机 (hostname + port)origin
获取 来源部分 (protocol + host)pathname
获取或设置 路径部分search
获取或设置 序列化查询部分hash
获取或设置 hash 部分password
获取或设置 密码username
获取或设置 用户名toString()
返回序列化的 URLtoJSON()
返回序列化的 URLsearchParams
获取 URLSearchParams 对象const { URL } = require('url');const myURL = new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');console.log('href', myURL.href); // https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash// 类似地,依次获取其他属性
URLSearchParams
接口 提供对查询参数的读写权限,便于对 URL 查询字符串进行操作。
new URLSearchParams([object])
实例化,传入查询字符串或对象append
、delete
、get
、getAll
、has
、set
等const { URL, URLSearchParams } = require('url');const myURL = new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');const params = new URLSearchParams(myURL.searchParams);// 调用方法进行查询参数操作
parse(str[, sep[, eq[, options]]])
stringify(obj[, sep[, eq[, options]]])
const querystring = require('querystring');const params = querystring.parse('name=aaa&age=90&sex=male&change=true');console.log(params); // {name: "aaa", age: "90", sex: "male", change: "true"}const newStr = querystring.stringify(params, ';', '*');console.log(newStr); // name*aaa;age*90;sex*male;change*true
通过合理运用 url 和 querystring 模块,可以显著提升项目实用性,简化日常开发任务。
转载地址:http://bbvoz.baihongyu.com/