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

  • 相关阅读:
    java循环控制语句loop使用
    可实现的全局唯一有序ID生成策略
    ElasticSearch使用RestHighLevelClient进行搜索查询
    基于Redis实现分布式定时任务调度
    python脚本生成exe程序
    敏捷开发--工作流程的梳理
    React-菜鸟学习笔记(二)
    React-菜鸟学习笔记(一)
    ZooKeeper-基础介绍
    常用排序算法的Java实现与分析
  • 原文地址:https://www.cnblogs.com/llc-url/p/7954370.html
Copyright © 2020-2023  润新知