nodejs URL 详解

本文介绍了如何使用.parse方法将URL字符串转换为URL对象,并详细解释了各参数的作用。此外,还介绍了如何利用.resolve方法拼接URL以及.format方法将URL对象转换回字符串形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 的 “#” 后面部分(包括 # 符号)
 

 

转载于:https://www.cnblogs.com/xiaofenguo/p/5689036.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值