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模块的三种方法就讲到这里了,不太全面的地方大家可以继续查阅其它资料哦。

  • 相关阅读:
    固定sql语句传参批量查询数据库脚本
    超多行数据纵向编辑
    takes 3 positional arguments but 4 were given错误
    使用PMD进行代码审查(转)
    WebADI应用到Office 2016 64-bit
    SVN 提交代码时强制加入注释内容
    DOCKER初体验
    "make_path" is not exported by the File::Path modul
    perl 调用shell脚本
    scp 上传文件到多个服务器节点
  • 原文地址:https://www.cnblogs.com/llc-url/p/7954370.html
Copyright © 2011-2022 走看看