node.js中url模块

在node服务端,如果使用的是get请求,想对请求进行链接进行解析的话,可以使用url模块,解析出每一个参数属性。

  • url模块的使用

1.cd到项目路径 使用npm安装url模块

2.在工程中引用url模块,

var url = require('url');
  • url的功能

1)解析请求的链接 url.parse(path,boolean),path->需要解析的URL路径,boolean->解析的路径参数 是否转变成JSON格式,默认是false ,当为true的时候,query字段被解析成参数字典形式,为false时,还是保留字符串形式。

var originURL = 'http://user:[email protected]:8080/p/a/t/h?query=string#hash';
var parseURL = parseUrl(originURL,true);
console.log(JSON.stringify(parseURL)+'解析parseURL');

解析结果:

{"protocol":"http:",
	"slashes":true,
	"auth":"user:pass",
	"host":"host.com:8080",
	"port":"8080",
	"hostname":"host.com",
	"hash":"#hash",
	"search":"?query=string",
	"query":{"query":"string"},
	"pathname":"/p/a/t/h",
	"path":"/p/a/t/h?query=string",
	"href":"http://user:[email protected]:8080/p/a/t/h?query=string#hash"
}
{"protocol":"http:",
"slashes":true,
"auth":"user:pass",
"host":"host.com:8080",
"port":"8080",
"hostname":"host.com",
"hash":"#hash",
"search":"?query=string&user=test",
"query":"query=string&user=test",
"pathname":"/p/a/t/h",
"path":"/p/a/t/h?query=string&user=test",
"href":"http://user:[email protected]:8080/p/a/t/h?query=string&user=test#hash"
}

2)可以将一个HTTP请求路径的字典 转化成 字符串请求链接,使用url.format(json字典)

var URLJson ={"protocol":"http:",
	"slashes":true,
	"auth":"user:pass",
	"host":"host.com:8080",
	"port":"8080",
	"hostname":"host.com",
	"hash":"#hash",
	"search":"?query=string",
	"query":{"query":"string"},
	"pathname":"/p/a/t/h",
	"path":"/p/a/t/h?query=string",
	"href":"http://user:[email protected]:8080/p/a/t/h?query=string#hash"
};
console.log(url.format(URLJson)+"连接字典拼接字符串");

拼接的请求路径结果: 

3)url使用函数resole(path1,path2),进行路径的拼接

var  resolveURL= url.resolve('http://www.baidu.com','tieba/xiaofeiniao/test');
console.log(resolveURL+"路径拼接");

拼接的请求路径结果:

测试代码库:https://github.com/ioszhanghui/NodeDemo

参考学习博客:

https://www.cnblogs.com/whiteMu/p/5983125.html

猜你喜欢

转载自blog.csdn.net/ioszhanghui/article/details/90289445