码迷,mamicode.com
首页 > Web开发 > 详细

nodejs URL 详解

时间:2016-07-20 17:41:40      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

1 我们可以使用.parse方法来将一个URL字符串转换为URL对象

例如:

url.parse(‘http://user:pass@host.com:8080/p/a/t/h?query=string#hash‘);
/* =>
{ protocol: ‘http:‘,
  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:pass@host.com:8080/p/a/t/h?query=string#hash‘ }
*/

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])

 

接收参数:

 

urlStr                                       url字符串

 

parseQueryString                   为true时将使用查询模块分析查询字符串,默认为false

 

slashesDenoteHost               

 

默认为false,//foo/bar 形式的字符串将被解释成 { pathname: ‘//foo/bar‘ }

 

如果设置成true,//foo/bar 形式的字符串将被解释成  { host: ‘foo‘, pathname: ‘/bar‘ }

例子:

 

var url = require(‘url‘);
var a = url.parse(‘http://example.com:8080/one?a=index&t=article&m=default‘);
console.log(a);
 
//输出结果:
{
    protocol : ‘http‘ ,
    auth : null ,
    host : ‘example.com:8080‘ ,
    port : ‘8080‘ ,
    hostname : ‘example.com‘ ,
    hash : null ,
    search : ‘?a=index&t=article&m=default‘,
    query : ‘a=index&t=article&m=default‘,
    pathname : ‘/one‘,
    path : ‘/one?a=index&t=article&m=default‘,
    href : ‘http://example.com:8080/one?a=index&t=article&m=default‘
}

如果parseQueryString 设置为true  url对象中的query会变成一个对象,如:  query:{a:"index",t::"article",m:"default"}

.resolve方法可以用于拼接URL

url.resolve(‘http://www.example.com/foo/bar‘, ‘../baz‘);
/* =>
 
http://www.example.com/baz
 
*/

3 反过来,.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‘
*/

 

 

 

URL 参数说明

     protocol: ‘http:‘,
     slashes: true,
     auth: null,
     host: ‘localhost:8888‘,
     port: ‘8888‘,
     hostname: ‘localhost‘,
     hash: null,
     search: ‘?name=bigbear&memo=helloworld‘,
     query: ‘name=bigbear&memo=helloworld‘,
     pathname: ‘/bb‘,
     path: ‘/bb?name=bigbear&memo=helloworld‘,
     href: ‘http://localhost:8888/bb?name=bigbear&memo=helloworld‘
 } 
 
  protocol: 请求协议
 
  host: URL主机名已全部转换成小写, 包括端口信息
 
  auth:URL中身份验证信息部分
 
  hostname:主机的主机名部分, 已转换成小写
 
  port: 主机的端口号部分
 
  pathname: URL的路径部分,位于主机名之后请求查询之前
 
  search: URL 的“查询字符串”部分,包括开头的问号。
 
  path: pathname 和 search 连在一起。
 
  query: 查询字符串中的参数部分(问号后面部分字符串),或者使用 querystring.parse() 解析后返回的对象。
 
  hash: URL 的 “#” 后面部分(包括 # 符号)
 

 

nodejs URL 详解

标签:

原文地址:http://www.cnblogs.com/xiaofenguo/p/5689036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!