zoukankan      html  css  js  c++  java
  • url模块

    NodeJS之URL模块

      今天讲的是NodeJS里面的一个简单的小模块,即url模块;这个url模块要使用的话,需要先引入。若只是在命令行里比如cmd或git bash等使用url这个模块的话,是不需要require进来的。直接使用便可

      const这个关键字是ES6里面定义的常量,不可以改变。

    1.const url = require("url");

      url总共提供了三个方法,分别是url.parse();  url.format();  url.resolve();

      1.url.parse(urlString[, parseQueryString[, slashesDenoteHost]])

      会返回一个解析后的对象,第一个参数为要解析的url地址,第二个参数为是否将query字符串解析成对象格式,第三个参数来控制在没有协议的情况下,是否解析域名等内容

      例子1:url.parse只传一个参数的情况

      url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash");
      /*
      返回值:
      {
        protocol: 'http:',
        slashes: true,
        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'
      }
     没有设置第二个参数为true时,query属性为一个字符串类型
    */
    

      例子2 : url.parse第二个参数为true的情况  

     url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash",true);
      /*
      返回值:
       {
        protocol: 'http:',
        slashes: true,
        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对象中,query属性为一个对象
     */
    

      

      2 url.format(urlObj) 

      将一个url解析后的对象还原成一个url地址
      参数:urlObj指一个url对象
      
    url.format({
        protocol:"http:",
        host:"182.163.0:60",
        port:"60"
    });
    /*
    返回值:
    'http://182.163.0:60'
    */
    

      

      3.url.resolve(from, to)

      可以将我们两段url解析成一个url地址
      
    url.resolve('http://www.baidu.com','/api/index.html');
    /*
    返回值:
    'http://www.baidu.com/api/index.html'
    */
    

      url模块的三种方法就讲到这里了,不太全面的地方大家可以继续查阅其它资料哦。

  • 相关阅读:
    js直接获取当前windows登陆账号---仅适用于IE
    Windows变量路径与通配符
    IDEA数据库生成Entity 带注释, 默认值
    BIM+区块链在建筑业施工过程结算的应用
    Java中动态规则的实现方式
    Git查看本地仓库关联关系以及清理无效远程分支
    Golang把字符串数组、[]interface{}打乱、切片乱序
    Golang将map数组按照指定字段排序
    Golang把时间和数字相乘报错invalid operation: second * time.Second (mismatched types int and time.Duration)
    Golang获取明日时间及距离明日凌晨的时间差
  • 原文地址:https://www.cnblogs.com/llc-url/p/7954370.html
Copyright © 2011-2022 走看看