node工程默认url_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字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值