在 Node.js 中,URL 模块用于处理和解析 URL(统一资源定位符)。URL 代表了网络资源的地址,常用于 HTTP 服务器开发和网络请求等场景。url 模块提供了实用的方法来解析、格式化和操作 URL。
在使用 URL 模块之前,需要先引入它:
const url = require('url');
url 模块的核心功能是解析 URL 字符串并返回 URL 对象,或者将 URL 对象格式化为 URL 字符串。
url.parse()url.parse() 方法用于解析 URL 字符串,返回一个 URL 对象。
语法:
url.parse(urlString, [parseQueryString], [slashesDenoteHost])
urlString: 要解析的 URL 字符串。parseQueryString: 布尔值(可选)。如果为 true,则 query 属性将使用 querystring 模块解析为对象(默认值为 false)。slashesDenoteHost: 布尔值(可选)。如果为 true,两个斜线(//)之间的字符将被解释为主机名(默认值为 false)。示例:
const url = require('url');
const myUrl = url.parse('https://www.example.com:8080/path/name?query=123#hash', true);
console.log(myUrl);
/*
{
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.example.com:8080',
port: '8080',
hostname: 'www.example.com',
hash: '#hash',
search: '?query=123',
query: { query: '123' },
pathname: '/path/name',
path: '/path/name?query=123',
href: 'https://www.example.com:8080/path/name?query=123#hash'
}
*/
解析后的对象包含以下属性:
href: 完整的 URL 字符串。protocol: URL 协议(包括冒号)。slashes: 布尔值,表示 URL 是否包含两个斜线。auth: URL 中的身份验证信息(如 username:password)。host: 完整的主机名(包括端口号)。port: 端口号。hostname: 主机名(不包括端口号)。hash: URL 中的哈希片段(包括 #)。search: 查询字符串(包括 ?)。query: 解析的查询对象或原始查询字符串(取决于 parseQueryString 参数)。pathname: 路径名。path: 路径名和查询字符串。url.format()url.format() 方法用于将 URL 对象格式化为 URL 字符串。
语法:
url.format(urlObject)
urlObject: 一个具有 URL 属性的对象。示例:
const url = require('url');
const urlObject = {
protocol: 'https:',
hostname: 'www.example.com',
port: 8080,
pathname: '/path/name',
search: '?query=123'
};
const myUrl = url.format(urlObject);
console.log(myUrl); // 输出: 'https://www.example.com:8080/path/name?query=123'
URL 类Node.js 8.0.0 之后,推荐使用 WHATWG 的 URL API,它提供了一个更现代和强大的 URL 操作方式。
通过 URL 类创建一个 URL 实例可以更加方便地操作和处理 URL。
语法:
const myUrl = new URL(input[, base]);
input: 要解析的绝对或相对 URL。base: 可选的基础 URL,用于解析相对 URL。示例:
const { URL } = require('url');
const myUrl = new URL('https://www.example.com:8080/path/name?query=123#hash');
console.log(myUrl);
/*
URL {
href: 'https://www.example.com:8080/path/name?query=123#hash',
origin: 'https://www.example.com:8080',
protocol: 'https:',
username: '',
password: '',
host: 'www.example.com:8080',
hostname: 'www.example.com',
port: '8080',
pathname: '/path/name',
search: '?query=123',
searchParams: URLSearchParams { 'query' => '123' },
hash: '#hash'
}
*/
URL 实例提供了以下属性:
href: 完整的 URL 字符串。origin: URL 的源(协议、主机名和端口)。protocol: URL 的协议(包括冒号)。username 和 password: URL 中的身份验证信息。host: 完整的主机名(包括端口号)。hostname: 主机名(不包括端口号)。port: 端口号。pathname: 路径名。search: 查询字符串(包括 ?)。searchParams: 一个 URLSearchParams 对象,表示查询参数。hash: URL 的哈希片段(包括 #)。URL 类提供了 URLSearchParams 对象用于操作查询参数。
示例:
const { URL } = require('url');
const myUrl = new URL('https://www.example.com/path/name?query=123');
myUrl.searchParams.append('newParam', '456'); // 添加新参数
console.log(myUrl.searchParams.toString()); // 输出: 'query=123&newParam=456'
myUrl.searchParams.set('query', '789'); // 设置参数的新值
console.log(myUrl.searchParams.toString()); // 输出: 'query=789&newParam=456'
console.log(myUrl.searchParams.get('query')); // 输出: '789'
myUrl.searchParams.delete('newParam'); // 删除参数
console.log(myUrl.searchParams.toString()); // 输出: 'query=789'
URL 事件在 Node.js 中,URL 本身并没有事件,但 URL 通常用于创建 HTTP 服务器,而 HTTP 服务器可以监听多个事件来处理请求和响应。例如:
const http = require('http');
const { URL } = require('url');
const server = http.createServer((req, res) => {
const myUrl = new URL(req.url, `http://${req.headers.host}`);
console.log('Pathname:', myUrl.pathname); // 获取路径名
console.log('Search Params:', myUrl.searchParams); // 获取查询参数
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, world!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
在这个例子中,服务器监听客户端请求,并使用 URL 对象解析请求的 URL。
Node.js 提供了强大的 URL 模块和 URL 类,允许开发者轻松解析和操作 URL 字符串。url.parse() 和 url.format() 是经典的方法,但在新代码中建议使用 WHATWG 的 URL API,因其更强大和现代化。通过这些工具,可以方便地获取 URL 的各个部分、操作查询参数,并在网络应用程序中处理 URL。