node.js中的⽹络地址URL

步骤:

        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

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值