url模块和querystring模块

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)) ;

  运行结果·如下:

    name=bigbear&memo=helloworld
    {
      name: 'bigbear',
      memo: 'helloworld'
    }
 
 

 

转载于:https://www.cnblogs.com/yymb/p/5760472.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值