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)

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