沐鳴註冊網站_Node中url模塊的使用
URL模塊是Nodejs的核心模塊之一,用於解析url字符串和url對象
1.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字符串
站長推薦
1.雲服務推薦: 國內主流雲服務商,各類雲產品的最新活動,優惠券領取。地址:阿里雲騰訊雲華為雲
2.廣告聯盟: 整理了目前主流的廣告聯盟平台,如果你有流量,可以作為參考選擇適合你的平台點擊進入
鏈接: http://www.fly63.com/article/detial/8360