Node中url模块的使用

URL模块是NodeJS的核心模块之一,用于解析url字符串和url对象

url.parse(url_str[,boolean])

url.parse(url_str[,boolean])用于将url字符串转为对象格式。该方法有两个参数,第一个参数为url字符串,第二个为布尔值,可以不写,表示是否也将query转为对象

url.parse(url_str)

//注意  以下代码只能在node中运行
//定义一个url字符串
var url_str="http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa"
//1、引入url模块
var url = require("url")
	//使用url.parse()方法将url字符串转化为对象
	var obj = url.parse(url_str)
	console.log(obj)
	//node中输出结果如下
	// Url {
	//   protocol: 'http:',
	//   slashes: true,
	//   auth: null,
	//   host: 'localhost:3000',
	//   port: '3000',
	//   hostname: 'localhost',
	//   hash: '#aaa',
	//   search: '?a=1&b=2&c=3',
	//   query: 'a=1&b=2&c=3',
	//   pathname: '/html/index.html',
	//   path: '/html/index.html?a=1&b=2&c=3',
	//   href: 'http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa' }

可以看到,在不写第二个参数时,默认为false,即不将query转为对象

url.parse(url_str,true)

var obj1 = url.parse(url_str,true)
	console.log(obj1)
	// Url {
	//   protocol: 'http:',
	//   slashes: true,
	//   auth: null,
	//   host: 'localhost:3000',
	//   port: '3000',
	//   hostname: 'localhost',
	//   hash: '#aaa',
	//   search: '?a=1&b=2&c=3',
	//   query: { a: '1', b: '2', c: '3' },
	//   pathname: '/html/index.html',
	//   path: '/html/index.html?a=1&b=2&c=3',
	//   href: 'http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa' }

可以看到,当添加第二个参数且值为true时,会将query也转为对象
#2、url.format()用于将url对象转为字符串
我们将上面的url对象obj1转为url字符串

//使用url的format方法将url对象转为字符串
	var url_str1 = url.format(obj1)
	console.log(url_str1)
	//node输出结果如下:
	// http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa

可以看到,使用url.format()方法又将url对象转为了 url字符串

posted @   Silence_1018  阅读(11)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示