以下是一些关于 Node.js 中 url 模块的基本用法:
1. 解析 URL 字符串:
const url = require('url');
const urlString = 'https://www.example.com:8080/path?query=param#fragment';
const parsedUrl = url.parse(urlString, true);
console.log('Parsed URL:', parsedUrl);
2. 构建 URL 对象:
const url = require('url');
const urlObject = {
protocol: 'https:',
hostname: 'www.example.com',
port: 8080,
pathname: '/path',
search: '?query=param',
hash: '#fragment'
};
const constructedUrl = url.format(urlObject);
console.log('Constructed URL:', constructedUrl);
3. 提取 URL 的各个部分:
const url = require('url');
const urlString = 'https://www.example.com:8080/path?query=param#fragment';
const { protocol, host, pathname, search, hash } = url.parse(urlString);
console.log('Protocol:', protocol);
console.log('Host:', host);
console.log('Pathname:', pathname);
console.log('Search:', search);
console.log('Hash:', hash);
4. 处理相对路径:
const url = require('url');
const baseUrl = 'https://www.example.com/path';
const resolvedUrl = url.resolve(baseUrl, '../newPath');
console.log('Resolved URL:', resolvedUrl);
5. URLSearchParams:
URLSearchParams 是用于处理 URL 查询参数的类。
const { URLSearchParams } = require('url');
const params = new URLSearchParams('key1=value1&key2=value2');
params.append('key3', 'value3');
params.set('key2', 'newvalue2');
console.log('Updated Query String:', params.toString());
这些示例展示了 Node.js 中 url 模块的基本用法。这个模块在处理和操作 URL 时非常有用,尤其在构建 web 服务器或处理 web 请求时经常会用到。
转载请注明出处:http://www.zyzy.cn/article/detail/4786/Node.js