对于一个url: const urlStr = "https://m.shop.com/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099#detail"
import url from 'url';
import qs from 'querystring'
const url = url.parse(urlStr)
const query = qs.parse(url.query)
如果你在nodejs 11.0以后的版本上使用,编译器会提示已过期
(since v11.0.0 - Use the WHATWG URL API
),并推荐你使用URL
.
这是因为nodejs的url.parse
方法采用的传统的urlObject
,不符合URL现存标准-WHATWG URL API,因此弃用了。同时
url.format()
, url.resolve()
也弃用了。
`WHATWG`是国际权威的技术标准组织
使用URL
类对url进行操作,详细文档见
const url1 = new URL(urlStr)
const name: string = url1.searchParams.get('name');
对比url模块
和URL类
分析上面的url
属性 | url模块 | URL类 |
---|---|---|
protocol | ✅ | ✅ |
host | ✅ | ✅ |
port | ✅ | ✅ |
hostname | ✅ | ✅ |
search | ✅ | ✅ |
query | ✅ | - |
path | ✅ | - |
pathname | ✅ | ✅ |
href | ✅ | ✅ |
hash | ✅ | ✅ |
origin | - | ✅ |
可以看出来,只有三个字段不同,分别是query
,path
,origin
,下图展示区别
注:
- 上下相同颜色为统一属性对比
- 例如:
url.search
和URL.searchParams
是相似的属性,放在一起比对,颜色相同。
打印两个对象的输出
// url模块,url.parse('link')
{
protocol: 'https:',
slashes: true,
auth: null,
host: 'm.shop.com',
port: null,
hostname: 'm.shop.com',
hash: '#detail',
search: '?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
query: 'id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
pathname: '/home/share',
path: '/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
href: 'https://m.shop.com/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099#detail'
}
// new URL()
{
href: 'https://m.shop.com/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099#detail',
origin: 'https://m.shop.com',
protocol: 'https:',
username: '',
password: '',
host: 'm.shop.com',
hostname: 'm.shop.com',
port: '',
pathname: '/home/share',
search: '?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
searchParams: URLSearchParams {
'id' => '4433',
'name' => '李备',
'directCompanyId' => '',
'mobile' => '18951431099' },
hash: '#detail'
}
参考文献: