【nodejs】URL模块

new URL(input, [base])

base验证input的origin是否符合预期

let myUrl = new URL('test/index.html', 'https://example.com');
// https://example.com/test/index.html

myUrl = new URL('http://Example.com/test/index.html', 'https://example.com');
// http://example.com/test/index.html

URL格式

URL {
  href: 'http://example.com/test/index.html',
  origin: 'http://example.com',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'example.com',
  hostname: 'example.com',
  port: '',
  pathname: '/test/index.html',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

URLSearchParams

创建

let params;
params = new URLSearchParams('user=abc&query=xyz');
params = new URLSearchParams('?user=abc&query=xyz');
params = new URLSearchParams({ user: 'abc', query: ['first', 'second'] });
params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second'],
]);

api

params.append('xxx', 123);
params.delete('user');
params.forEach((v, key) => {
  console.log(v, key);
});
params.get('user');
params.getAll('query');
params.has('user');
params.keys();
// 如果存在任何名称为 name 的预先存在的名称-值对,则将第一个此类对的值设置为 value 并删除所有其他名称。 如果没有,则将名称-值对追加到查询字符串。
params.set('user', 'def');
params.sort();
params.values();
params.toString();
原文地址:https://www.cnblogs.com/zhoulixue/p/15391969.html