1、URL类
url模块在v16的nodejs中已经明确被废弃,在将来的升级node中,可能被不支持。
官网建议在废弃url、querystring模块
后,采用URL类
去替代。
1.1、图示 URL 各部分
1.2、旧版的url模块(node16之前版本)
作用:url 模块
是用于处理和解析 URL 的模块,能够将 URL 字符串解析为 URL 对象
并反向操作,即将 URL 对象转换为 URL 字符串。
const url = require('url');
常用的方法:
- parse(urlString[, parseQueryString[, slashesDenoteHost]]):将一个 URL 字符串解析成一个 URL 对象。
- format(urlObject):将一个 URL 对象格式化成一个 URL 字符串。
- resolve(from, to):解析一个相对路径,返回完整的 URL 字符串。
const url = require('url');
// 解析 URL 字符串
const urlString = 'https://www.example.com/path?query=string#hash';
const urlObj = url.parse(urlString);
console.log(urlObj);
// Url {
// protocol: 'https:',
// slashes: true,
// auth: null,
// host: 'www.example.com',
// port: null,
// hostname: 'www.example.com',
// hash: '#hash',
// search: '?query=string',
// query: 'query=string',
// pathname: '/path',
// path: '/path?query=string',
// href: 'https://www.example.com/path?query=string#hash'
// }
// 将 URL 对象转换为字符串
const urlObject = {
protocol: 'https:',
slashes: true,
hostname: 'www.example.com',
pathname: '/path',
search: '?query=string',
hash: '#hash'
};
const newUrl = url.format(urlObject);
console.log(newUrl);
// https://www.example.com/path?query=string#hash
// 解析相对路径
const from = 'https://www.example.com/path';
const to = '../file.txt';
const resolvedUrl = url.resolve(from, to);
console.log(resolvedUrl);
// https://www.example.com/file.txt
参数 | 描述 | 示例 |
---|---|---|
href | 解析前的完整原始 URL,协议名和主机名已转为小写 | http://user:pass@host.com:8080/p/a/t/h?query=string#hash |
protocol | 请求协议,小写 | http: |
slashes | 协议的":“号后是否有”/" | true or false |
host | URL主机名,包括端口信息,小写 | ‘host.com:8080’ |
auth | URL中的认证信息 | ‘user:pass’ |
hostname | 主机名,小写 | ‘host.com’ |
port | 主机的端口号 | ‘8080’ |
pathname | URL中路径 | ‘/p/a/t/h’ |
search | 查询对象,即:queryString,包括之前的问号“?” | ‘?query=string’ |
path | pathname 和 search的合集 | ‘/p/a/t/h?query=string’ |
query | 查询字符串中的参数部分(问号后面部分字符串) | ‘query=string’ or {‘query’:‘string’} |
hash | 锚点部分(即:“#”及其后的部分) | ‘#hash’ |
1.3、新版的url模块(node16版本之后)
注意点:在v16及以上中,nodejs已经废弃了url/querystring模块
需要被URL类
给替代
语法:newURL(path[,baseUrl])
- path:需要被URL类解析的路径
- baseUrl:主机名,如果path中已经带有域名,则baseUrl可以不写
URL类不是模块,不需要导入
1、创建URL对象
const { URL } = require('url');
const myUrl = new URL('https://www.example.com/path/?query=value');
console.log(myUrl);
// Output: URL {
// href: 'https://www.example.com/path/?query=value',
// origin: 'https://www.example.com',
// protocol: 'https:',
// username: '',
// password: '',
// host: 'www.example.com',
// hostname: 'www.example.com',
// port: '',
// pathname: '/path/',
// search: '?query=value',
// searchParams: URLSearchParams { 'query' => 'value' },
// hash: ''
// }
2、获取 URL 的各个部分
console.log(myUrl.protocol); // return: 'https:'
console.log(myUrl.host); // return: 'www.example.com'
console.log(myUrl.pathname); // return: '/path/'
console.log(myUrl.search); // return: '?query=value'
console.log(myUrl.hash); // return: ''
3、修改 URL 的各个部分
myUrl.hash = 'section1';
console.log(myUrl.href);
// return: 'https://www.example.com/path/?query=value#section1'
4、new URLSearchParams
new URLSearchParams()
是Web API中的一个构造函数,用于创建一个表示URL查询参数的对象
。
它可以接受一个查询字符串作为参数,也可以通过键值对、数组、对象等方式来添加查询参数。
该对象可以轻松地对查询参数进行增删改查,方便进行URL的构造和解。
现在常被用来当做 替代queryString 板块。
const params = new URLSearchParams('?name=Lucy&age=18');
console.log(params.has('name')); // true
console.log(params.get('age')); // 18
console.log(params.toString()); // 'name=Lucy&age=18'
params.set('gender', 'female');
console.log(params.toString()); // 'name=Lucy&age=18&gender=female'
2、queryString 模块(node16版本之前)
作用:查询字符串主要由两个方法和内置格式化方法组成,一个是将对象转换为字符串,一个则是相反,将字符串转换为对象:
方法 | 描述 |
---|---|
querystring.stringify(obj, [sep], [eq]) | 将JSON对象格式化为查询字符串格式的字符串 |
querystring.parse(str, [sep], [eq], [options]) | 根据“&”和“=”将字符串进行分割,反序列化为JSON对象 |
1、stringify
作用: 对象转为query字符串
将JSON对象格式化为查询字符串格式的字符串,默认的分隔符为:“&”和“=”,具体可以看一下以下代码:
const querystring=require('querystring')
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'
对象转为query字符串
const querystring=require('querystring')
querystring.stringify({foo:'bar',abc:'xyz'})
querystring.encode({foo:'bar',abc:'xyz'})
//foo=bar&abc=xyz
//foo=bar&abc=xyz
2、parse
作用:将query字符串转为对象
根据“&”和“=”将字符串进行分割,反序列化为JSON对象,而options包含的maxKeys默认设置为1000,如果将其设置为0则表示没这个限制。
const querystring=require('querystring')
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
将query字符串转为对象
const querystring=require('querystring')
//query字符串转为对象
querystring.parse('foo=bar&abc=xyz')
querystring.decode('foo=bar&abc=xyz')
//{ foo: 'bar', abc: 'xyz' }
// { foo: 'bar', abc: 'xyz' }