美文网首页
nodejs url 内置模块

nodejs url 内置模块

作者: 暴躁程序员 | 来源:发表于2022-01-20 09:04 被阅读0次

    1. parse 反序列化(将url字符串解析成对象)

    语法:url.resolve (url字符串,query参数是否进行querystring反序列化解析,可省略)

    const url = require("url");
    const url_str = "http://localhost:8080/api/canda/user?username=青龙&password=123456&code=10086";
    const result1 = url.parse(url_str)
    console.log('result1: ', result1);
    const result2 = url.parse(url_str,true)
    console.log('result2: ', result2);
    

    结果如下,query参数在第二个参数为true的情况下会被反序列化成对象

    result1:  Url {
      protocol: 'http:',
      slashes: true,
      auth: null,
      host: 'localhost:8080',
      port: '8080',
      hostname: 'localhost',
      hash: null,
      search: '?username=青龙&password=123456&code=10086',
      query: 'username=青龙&password=123456&code=10086',  
      pathname: '/api/canda/user',
      path: '/api/canda/user?username=青龙&password=123456&code=10086',
      href: 'http://localhost:8080/api/canda/user?username=青龙&password=123456&code=10086'
    }
    result2:  Url {
      protocol: 'http:',
      slashes: true,
      auth: null,
      host: 'localhost:8080',
      port: '8080',
      hostname: 'localhost',
      hash: null,
      search: '?username=青龙&password=123456&code=10086',
      query: [Object: null prototype] {
        username: '青龙',
        password: '123456',
        code: '10086'
      },
      pathname: '/api/canda/user',
      path: '/api/canda/user?username=青龙&password=123456&code=10086',
      href: 'http://localhost:8080/api/canda/user?username=青龙&password=123456&code=10086'
    }
    

    2. format 序列化(将url对象解析成url字符串)

    语法:url.resolve (url对象)

    const url = require("url");
    const url_obj = {
        protocol: 'http:',
        slashes: true,
        auth: null,
        host: 'localhost:8080',
        port: '8080',
        hostname: 'localhost',
        hash: null,
        search: '?username=青龙&password=123456&code=10086',
        query:  {
          username: '青龙',
          password: '123456',
          code: '10086'
        },
        pathname: '/api/canda/user',
        path: '/api/canda/user?username=青龙&password=123456&code=10086',
        href: 'http://localhost:8080/api/canda/user?username=青龙&password=123456&code=10086'
      }
    const result = url.format(url_obj)
    console.log(result); // 结果: http://localhost:8080?username=青龙&password=123456&code=10086
    

    3. resolve url路径拼接(路由切换)

    语法:url.resolve (基础路径 , 拼接路径)

    const url = require("url");
    const a = 'localhost:8080/';
    const b = 'api/scan/user'
    const c = 'api/scan/roles'
    const result1 = url.resolve(a,b)
    const result2 = url.resolve(a,c)
    console.log(result1); // 结果: localhost:8080/api/scan/user
    console.log(result2); // 结果: localhost:8080/api/scan/roles
    

    相关文章

      网友评论

          本文标题:nodejs url 内置模块

          本文链接:https://www.haomeiwen.com/subject/fkgmcrtx.html