Nodejs教程13:URL模块

本文深入讲解了使用Node.js中的URL模块解析和操作URL的方法。包括如何利用url.parse将URL分解成各个组成部分,以及如何通过URL构造函数创建包含解析数据的对象。示例代码展示了如何解析复杂的URL,提取端口号、域名和查询参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

url.parse

URL模块用于对URL的解析,常用的是url.parse方法。

假设有一个url为https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4,可以用url.parse方法进行解析。

示例代码:/lesson13/url.js

const url = require('url')

const str = 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4'

console.log(url.parse(str))

打印结果如下:

Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.google.com:8080',
  port: '8080',
  hostname: 'www.google.com',
  hash: null,
  search: '?x=1&y=2&y=3&y=4',
  query: 'x=1&y=2&y=3&y=4',
  pathname: '/a/b',
  path: '/a/b?x=1&y=2&y=3&y=4',
  href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4' }

可以看到url的信息如端口号、域名、query参数等都被解析出来了。

如果需要将query参数转为对象,则可以为url.parse函数的第二个参数传true,如console.log(url.parse(str, true)),打印结果如下:

Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.google.com:8080',
  port: '8080',
  hostname: 'www.google.com',
  hash: null,
  search: '?x=1&y=2&y=3&y=4',
  query: [Object: null prototype] { x: '1', y: [ '2', '3', '4' ] },
  pathname: '/a/b',
  path: '/a/b?x=1&y=2&y=3&y=4',
  href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4' }

同时可以看到y=2&y=3&y=4参数被解析为了y: [ ‘2’, ‘3’, ‘4’ ]。

new URL()

除了用url.parse方法解析url,还可以通过构造函数URL,创建一个实例,其中带有解析后的数据。

实例有一个toString方法,可以将实例解析为字符串url。

示例代码:/lesson13/url.js

代码如下:

const { URL } = require('url')
const urlObj = new URL(str)

console.log(urlObj)
console.log(urlObj.toString())

打印结果为:

URL {
  href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4',
  origin: 'https://www.google.com:8080',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'www.google.com:8080',
  hostname: 'www.google.com',
  port: '8080',
  pathname: '/a/b',
  search: '?x=1&y=2&y=3&y=4',
  searchParams:
   URLSearchParams { 'x' => '1', 'y' => '2', 'y' => '3', 'y' => '4' },
  hash: '' }
  
https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4	// toString方法解析出的url
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值