• 【Node.js】URL 模块


    自动重启服务器的插件nodemon: npm i -g nodemon。或者 node-dev 也可以:npm i -g node-dev

    parse,format,resolve 为旧版写法。

    parse

    import url from 'url'
    const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
    const parsedStr = url.parse(urlString)
    console.log(parsedStr)
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    使用 const parsedStr = url.parse(urlString, true) 时,会将 query 转换为对象的形式:

    在这里插入图片描述

    format

    import url from 'url'
    const urlObject = {
      protocol: 'https:',
      slashes: true,
      auth: null,
      host: 'www.baidu.com:443',
      port: '443',
      hostname: 'www.baidu.com',
      hash: '#tag=110',
      search: '?id=8&name=mouse',
      query: { id: '8', name: 'mouse' },
      pathname: '/ad/index.html',
      path: '/ad/index.html?id=8&name=mouse'
    }
    const parsedObj = url.format(urlObject)
    console.log(parsedObj)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    resolve

    import url from 'url'
    // url.resolve(from, to)
    var a = url.resolve('/one/two/three', 'four')
    var e = url.resolve('/one/two/three/', 'four')
    var b = url.resolve('http://example.com/', '/one')
    var c = url.resolve('http://example.com/one', '/two')
    var d = url.resolve('http://example.com/one/', 'three')
    console.log(a + "," + e + "," + b + "," + c + "," + d)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在这里插入图片描述

    总结一下就是:1. 没有域名的地址,在地址最后一个 / 后进行拼接。2. 有域名的地址,to 含有 / ,直接拼接到域名之后,没有/,拼接到 from 的后面。

    新版写法 new URL。

    import http from 'http'
    import url from 'url'
    // 创建本地服务器接收数据
    const server = http.createServer((req, res) => {
      const myUrl = new URL(req.url, 'http://127.0.0.1:3000')
      console.log(myUrl)
      res.writeHead(200, { 
        'Content-Type': 'application/json' 
      })
      res.end(JSON.stringify({
        data: "hello"
      }))
    })
    server.listen(8000,()=> {
      console.log("server is running")
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    const myURL = new URL('/foo', 'https://example.org/');
    // https://example.org/foo
    
    • 1
    • 2

    查询参数

    const myURL = new URL('https://example.org/abc?foo=~bar');
    console.log(myURL.search);  // ?foo=~bar
    
    • 1
    • 2

    其他用法都在官方文档,写的很清楚。Node.js 中文网

  • 相关阅读:
    基于Java swing+mysql+eclipse的【水电费管理系统】
    CTF-php特性绕过
    【Docker】Docker安装Nginx配置静态资源
    回溯算法 | N皇后 | leecode刷题笔记
    Go HTTP 调用(下)
    php output_buffering 缓存使用
    mybatisplus快速实现动态数据源切换
    三维虚拟沙盘数字全景沙盘M3DGIS系统开发教程第18课
    C++Qt开发——操作MySQL数据库
    基于瞬时无功功率ip-iq的谐波信号检测Simulink仿真
  • 原文地址:https://blog.csdn.net/XiugongHao/article/details/133688768