node.js的url解析和生成

Posted on 2020-04-09 16:15  猫头唔食鱼  阅读(324)  评论(0编辑  收藏  举报

1.url的解析,用url.parse(urlStr)

var url = 'localhost:8080/#/test'
var urlModel = require('url')
console.log(urlModel.parse(url));

打印结果:

Url {
  protocol: 'localhost:',
  slashes: null,
  auth: null,
  host: '8080',
  port: null,
  hostname: '8080',
  hash: '#/test',
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'localhost:8080/#/test'
}

 

2.url生成,url.format(obj)

var obj = {
    protocol: 'localhost:',
    slashes: null,
    auth: null,
    host: '8080',
    port: null,
    hostname: '8080',
    hash: '#/test',
    search: null,
    query: null,
    pathname: '/',
    path: '/',
    href: 'localhost:8080/#/test'
}

console.log(urlModel.format(obj));

打印结果:

localhost:8080/#/test