Node.js学习之地址解析模块URL的使用详解

2020-06-17 07:07:23易采站长站整理

var urlstr = "http://localhost:8888/bb?name=bigbear&memo=helloworld&memo=helloC";
console.log(
url.parse(urlstr, true)
)
/*
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:8888',
port: '8888',
hostname: 'localhost',
hash: null,
search: '?name=bigbear&memo=helloworld&memo=helloC',
query: { name: 'bigbear', memo: [ 'helloworld', 'helloC' ] },
pathname: '/bb',
path: '/bb?name=bigbear&memo=helloworld&memo=helloC',
href: 'http://localhost:8888/bb?name=bigbear&memo=helloworld&memo=helloC' }
*/

第三个参数对比

例子如下:


const url = require("url");
var urlstr = "//foo/bar ";
console.log(
url.parse(urlstr, true,true)
)
/*
输出:Url {
protocol: null,
slashes: true,
auth: null,
host: 'foo',
port: null,
hostname: 'foo',
hash: null,
search: '',
query: {},
pathname: '/bar',
path: '/bar',
href: '//foo/bar' }
*/

const url = require("url");
var urlstr = "//foo/bar ";
console.log(
url.parse(urlstr)
)
/*
输出:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '//foo/bar',
path: '//foo/bar',
href: '//foo/bar' }
*/

url模块化

将一个url对象转换成一个url字符串,url对象中的属性为

url.parse()
产生的对象的属性。

url.parse()
url.format()
互为逆操作。

例子如下:


const url = require("url");
var Urlobj = {
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:8888',
port: '8888',
hostname: 'localhost',
hash: null,
search: '?name=bigbear&memo=helloworld&memo=helloC',
query: { name: 'bigbear', memo: [ 'helloworld', 'helloC' ] },
pathname: '/bb',
path: '/bb?name=bigbear&memo=helloworld&memo=helloC',
}
console.log(
url.format(Urlobj)
)
//输出:http://localhost:8888/bb?name=bigbear&memo=helloworld&memo=helloC

路径解析:url.resolve(from, to)

url.resolve()
方法解决了目标URL相对于基本URL的方式类似于Web浏览器解决锚标记href。

官方手册例子:


url.resolve('/one/two/three', 'four');
// '/one/two/four'

url.resolve('http://example.com/', '/one');
// 'http://example.com/one'