node.js 中對url的處理

const url = require('url')
const URL = require('url').URL
const querystring = require('querystring')
// console.log(url)
// const myUrl = new URL('http://cmstest.cnlive.com:8768/witness/witnessTagList')
const myUrl = new URL("https://segmentfault.com/q/1010000009484815?_ea=1945039&name='tengxi'")
console.log(myUrl.searchParams)
// !!!!查詢參數可以用searchParams獲取, hash值可以先獲取hash值再用queryString獲取對象中的每一個屬性
// 根據瀏覽器的約定, URL 對象的所有屬性都是在類的原型上實現爲getter和setter,而不是作爲對象本身的數據屬性
// 在URL對象上delete任何屬性都不成功但是能返回true

let hash = myUrl.hash // 讀取url的hash
myUrl.hash = 'hash test' // 給url設置hash
// console.log(myUrl)

let origin = myUrl.origin
myUrl.origin = 'http://www.baidu.com' // origin是隻讀的,這句話寫了也白寫,也不報錯
// console.log(myUrl.origin)

// 端口值可以是數字或包含 0 到 65535(含)範圍內的數字字符串 超出範圍設置語句被忽略
// 給默認端口設置端口號會變成'' 格式不正確的端口號 設置無效 數字開頭加字母,字母忽略,數字當做端口號。非整數字只保留整數部分 科學計數法但沒超範圍,只保留小數點前數字作爲端口號
// 端口值可以是空字符串,實際端口號取決於協議種類
// "ftp"    21
// "file"    
// "gopher"    70
// "http"    80
// "https"    443
// "ws"    80
// "wss"    443

// 特殊協議規範是 ftp、 file、 gopher、 http、 https、 ws 和 wss
// 特殊和非特殊的協議不可以互相轉化

// 使用 url.search 設置來替換 URL 的整個查詢參數
const currentPage = new URL('https://www.zcfy.cc/article/node-js-tutorial-the-whatwg-url-parser-the-node-beginner-blog-3957.html?t=new')
currentPage.searchParams.append('homeData', 'homepage') // 給url增加查詢參數
currentPage.searchParams.delete('homeData') // 刪除url中的查詢參數
currentPage.searchParams.set('a', 'b') // 給url中增加查詢參數 &a=b
// console.log(currentPage)
let queryParams = currentPage.searchParams.get('t') // 獲取url中的查詢參數的值
// console.log(queryParams)
// 類似於vue中帶#的url,會被劃分到hash裏面去,用以上方法獲取不到查詢參數的值


const hashUrl = new URL('http://web.cms.cnlive.com/#/sp/edit?type=update&id=1179&noce_str=EVQO6ZG&name=%E5%93%81%E7%89%8C%E8%AF%B4&icon=https%3A%2F%2Fwjj.ys2.cnliveimg.com%2F1197%2Fimg_new%2F1569552702358.png&subtitle&spDesc&spLiveNotice&parentType=1&parentId=304&phone&imGroupId&groupType=false&tags=4,6&extension&enable=1&sid&spType&siteId=51&parentName')
let hashString = hashUrl.hash
// console.log('看看這個url的hash值')
// console.log(hashString)
let paramsObj = querystring.decode(hashString)
// console.log(paramsObj)
let formType    
for (let i in paramsObj) {
    if(i.includes('type')) {
        formType = paramsObj[i]
    }
}
console.log(formType)
console.log(paramsObj.icon)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章