url模块
我们可以使用.parse方法来将一个URL字符串转换为URL对象,示例如下。
1. URL各部分说明
var url = require('url'); //加载url模块
url.parse('http://www.baidu.com');
返回的结果为:
{ protocol: 'http:',
slashes: null,
auth: null,
host: null,
port: null, hostname: null, hash: null, search: null, query: null, pathname: 'www.baidu.com', path: 'www.baidu.com', href: 'http://www.baidu.com' }
parse函数的第二个参数是布尔类型,当参数为true时,会将查询条件query也解析成json格式的对象
parse函数的第三个参数也是布尔类型的,当参数为true,解析时会将url的”//”和第一个”/”之间的部分解析为主机名,示例如下:
var url = require('url');
url.parse('http://www.baidu.com/news',false,true);
返回的结果:
{ protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null, hostname: 'www.baidu.com', hash: null, search: null, query: null, pathname: '/news', path: '/news', href: 'http://www.baidu.com/news' }
protocol: 请求协议
host: URL主机名已全部转换成小写, 包括端口信息
auth:URL中身份验证信息部分
hostname:主机的主机名部分, 已转换成小写
port: 主机的端口号部分
pathname: URL的路径部分,位于主机名之后请求查询之前
search: URL 的“查询字符串”部分,包括开头的问号。
path: pathname 和 search 连在一起。
query: 查询字符串中的参数部分(问号后面部分字符串),或者使用 querystring.parse() 解析后返回的对象。
hash: URL 的 “#” 后面部分(包括 # 符号)
format方法允许将一个URL对象转换为URL字符串,示例如下。
代码如下:
url.format({
protocol: 'http:',
host: 'www.example.com',
pathname: '/p/a/t/h',
search: 'query=string'
});
/* =>
'http://www.example.com/p/a/t/h?query=string'
*/
.resolve方法可以用于拼接URL,示例如下。
代码如下:
url.resolve('http://www.example.com/foo/bar', '../baz');
/* =>
http://www.example.com/baz
*/
querystring模块
"QueryString" 模块用于实现URL参数字符串与参数对象的互相转换,来个栗子,如下所示:
var url = require('url');
var qs = require('querystring');
var queryUrl = " http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
queryUrl = url.parse(queryUrl).query ;
console.log(queryUrl) ;
console.log(qs.parse(queryUrl)) ;
var qs = require('querystring');
var queryUrl = " http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
queryUrl = url.parse(queryUrl).query ;
console.log(queryUrl) ;
console.log(qs.parse(queryUrl)) ;
运行结果·如下:
name=bigbear&memo=helloworld
{
name: 'bigbear',
memo: 'helloworld'
}
{
name: 'bigbear',
memo: 'helloworld'
}