步骤:
1. 引⼊url模块 const url = require("url");
2. 调⽤url相关API对URL地址进⾏处理
在 Node.js 中,可以使用内置的 url
模块来处理和解析网络地址(URL)。以下是三个简单的示例代码
示例:URL
const url = require('url');
const myURL = 'https://example.com:8080/path?query=string';
const urlAnalyze = new url.URL(myURL);
console.log(urlAnalyze);
// 打印结果
URL {
href: 'https://example.com:8080/path?query=string',
origin: 'https://example.com:8080',
protocol: 'https:',
username: '',
password: '',
host: 'example.com:8080',
hostname: 'example.com',
port: '8080',
pathname: '/path',
search: '?query=string',
searchParams: URLSearchParams { 'query' => 'string' },
hash: ''
}
示例: url.format(URL[, options])
const url = require('url');
const urlObject = {
protocol: 'https:',
hostname: 'example.com',
port: 8080,
pathname: '/path',
query: { query: 'string' },
};
const formattedUrl = url.format(urlObject);
console.log(formattedUrl);
示例: url.resolve(from,to)
onst url = require("url");
console.log(url.resolve("/one/two/three","four"));
console.log(url.resolve("/one/two/","four"));
console.log(url.resolve("http://www.baidu.com","/topic"));
console.log(url.resolve("http://www.baidu.com/one","topic"));
// 结果:
/one/two/four
/one/two/four
http://www.baidu.com/topic
http://www.baidu.com/topic
const resolvedUrl = url.resolve('https://example.com/path/', '../file.htm
l');
console.log(resolvedUrl);
// 结果:
https://example.com/file.html