nodejs URL 详解

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"}
2 .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 参数说明:
{
 
                     
                    
                 
                    
                 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号