Node.js 中的 URL 模块

发布于:2025-05-13 ⋅ 阅读:(12) ⋅ 点赞:(0)

一、URL 模块基础

1. 模块导入方式

// Node.js 方式
const url = require('url');

// ES 模块方式 (Node.js 14+ 或启用 ESM)
import * as url from 'url';

2. 核心功能

  • 解析 URL 字符串

  • 格式化 URL 对象

  • URL 处理工具方法

  • WHATWG URL 标准实现

二、URL 解析与构建

1. 传统解析方法 (Legacy API)

const urlObj = url.parse('https://example.com:8080/p/a/t/h?query=string#hash');

// 解析结果示例
{
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'example.com:8080',
  port: '8080',
  hostname: 'example.com',
  hash: '#hash',
  search: '?query=string',
  query: 'query=string',
  pathname: '/p/a/t/h',
  path: '/p/a/t/h?query=string',
  href: 'https://example.com:8080/p/a/t/h?query=string#hash'
}
参数解析模式
const urlObj = url.parse('https://example.com?foo=bar&abc=xyz', true);
// urlObj.query 结果为 { foo: 'bar', abc: 'xyz' }

2. WHATWG URL API (推荐)

const myURL = new URL('https://example.com:8080/p/a/t/h?query=string#hash');

// URL 对象属性
console.log(myURL.href);        // 完整URL
console.log(myURL.protocol);    // 'https:'
console.log(myURL.hostname);    // 'example.com'
console.log(myURL.port);        // '8080'
console.log(myURL.pathname);    // '/p/a/t/h'
console.log(myURL.search);      // '?query=string'
console.log(myURL.hash);        // '#hash'
console.log(myURL.origin);      // 'https://example.com:8080'
查询参数处理
const myURL = new URL('https://example.com/?user=abc&query=xyz');

// 获取查询参数
console.log(myURL.searchParams.get('user')); // 'abc'

// 设置查询参数
myURL.searchParams.set('page', '1');
console.log(myURL.href); 
// 'https://example.com/?user=abc&query=xyz&page=1'

// 遍历参数
myURL.searchParams.forEach((value, name) => {
  console.log(`${name}: ${value}`);
});

三、URL 格式化与操作

1. 格式化 URL 对象

// 传统方式
const formattedUrl = url.format({
  protocol: 'https',
  hostname: 'example.com',
  pathname: '/some/path',
  query: { page: 1, limit: 10 }
});
// 'https://example.com/some/path?page=1&limit=10'

// WHATWG 方式
const myURL = new URL('https://example.com');
myURL.pathname = '/new/path';
myURL.search = '?filter=latest';
console.log(myURL.href); 
// 'https://example.com/new/path?filter=latest'

2. URL 拼接

// 传统方式
const resolvedUrl = url.resolve('https://example.com/foo/bar', '../baz');
// 'https://example.com/baz'

// WHATWG 方式
const baseUrl = new URL('https://example.com/foo/bar');
const newUrl = new URL('../baz', baseUrl);
console.log(newUrl.href); 
// 'https://example.com/baz'

四、URLSearchParams 类

1. 基本用法

const params = new URLSearchParams('key1=value1&key2=value2');

// 添加参数
params.append('key3', 'value3');

// 获取参数
console.log(params.get('key1')); // 'value1'

// 检查存在
console.log(params.has('key2')); // true

// 删除参数
params.delete('key2');

// 转换为字符串
console.log(params.toString()); // 'key1=value1&key3=value3'

2. 高级操作

const params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second']
]);

// 获取所有值
console.log(params.getAll('query')); // ['first', 'second']

// 迭代参数
for (const [name, value] of params) {
  console.log(`${name}: ${value}`);
}

// 排序参数
params.sort();

五、实际应用场景

1. Web 服务器路由解析

const http = require('http');
const url = require('url');

http.createServer((req, res) => {
  const parsedUrl = url.parse(req.url, true);
  
  // 获取路径和查询参数
  const pathname = parsedUrl.pathname;
  const query = parsedUrl.query;
  
  if (pathname === '/search' && query.q) {
    // 处理搜索请求
  }
}).listen(3000);

2. 构建 API 端点

function buildApiUrl(base, endpoint, params) {
  const apiUrl = new URL(endpoint, base);
  Object.entries(params).forEach(([key, value]) => {
    apiUrl.searchParams.append(key, value);
  });
  return apiUrl.href;
}

const url = buildApiUrl('https://api.example.com', '/v1/products', {
  category: 'electronics',
  page: 2,
  limit: 20
});

3. 安全重定向验证

function safeRedirect(baseUrl, redirectPath) {
  try {
    const redirectUrl = new URL(redirectPath, baseUrl);
    // 验证是否同源
    if (redirectUrl.origin === new URL(baseUrl).origin) {
      return redirectUrl.href;
    }
    return baseUrl;
  } catch (e) {
    return baseUrl;
  }
}

六、注意事项与最佳实践

1. 安全性考虑

  • 始终验证用户提供的 URL

  • 处理 URL 解析错误

  • 警惕协议跳转 (http → https)

  • 注意编码问题 (防止 XSS)

2. 性能建议

  • 重用 URL 和 URLSearchParams 对象

  • 避免频繁解析相同 URL

  • 对大量参数使用 URLSearchParams 而不是字符串操作

3. 兼容性说明

  • 传统 API (url.parse()) 已弃用但仍在维护

  • WHATWG URL API 是现代标准实现

  • Node.js 10+ 完全支持 WHATWG URL

七、常见问题解决方案

1. 处理特殊字符

const myURL = new URL('https://example.com');
myURL.searchParams.set('query', 'some value with spaces');
console.log(myURL.href); 
// 'https://example.com/?query=some+value+with+spaces'

2. 获取不带查询的路径

const myURL = new URL('https://example.com/path?query=string');
console.log(myURL.pathname + myURL.hash); // '/path'

3. 比较 URL

function areUrlsEqual(url1, url2) {
  try {
    return new URL(url1).href === new URL(url2).href;
  } catch (e) {
    return false;
  }
}

URL 模块是 Node.js 中处理 Web 地址的核心工具,熟练掌握可以高效解决各种 URL 操作需求。WHATWG URL API 提供了更现代、更符合标准的实现方式,推荐在新项目中使用。


网站公告

今日签到

点亮在社区的每一天
去签到