Node中url模块的使用

URL模块是Nodejs的核心模块之一,用于解析url字符串和url对象

 

1.url.parse(url_str[,boolean])

url.parse(url_str[,boolean])用于将url字符串转为对象格式。该方法有两个参数,第一个参数为url字符串,第二个为布尔值,可以不写,表示是否也将query转为对象

url.parse(url_str)

//注意  以下代码只能在node中运行
//定义一个url字符串
var url_str="http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa"
//1、引入url模块
var url = require("url")
    //使用url.parse()方法将url字符串转化为对象
    var obj = url.parse(url_str)
    console.log(obj)
    //node中输出结果如下
    // Url {
    //   protocol: 'http:',
    //   slashes: true,
    //   auth: null,
    //   host: 'localhost:3000',
    //   port: '3000',
    //   hostname: 'localhost',
    //   hash: '#aaa',
    //   search: '?a=1&b=2&c=3',
    //   query: 'a=1&b=2&c=3',
    //   pathname: '/html/index.html',
    //   path: '/html/index.html?a=1&b=2&c=3',
    //   href: 'http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa' }
可以看到,在不写第二个参数时,默认为false,即不将query转为对象

电脑刺绣绣花厂 http://www.szhdn.com 广州品牌设计公司https://www.houdianzi.com

url.parse(url_str,true)

var obj1 = url.parse(url_str,true)
    console.log(obj1)
    // Url {
    //   protocol: 'http:',
    //   slashes: true,
    //   auth: null,
    //   host: 'localhost:3000',
    //   port: '3000',
    //   hostname: 'localhost',
    //   hash: '#aaa',
    //   search: '?a=1&b=2&c=3',
    //   query: { a: '1', b: '2', c: '3' },
    //   pathname: '/html/index.html',
    //   path: '/html/index.html?a=1&b=2&c=3',
    //   href: 'http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa' }
可以看到,当添加第二个参数且值为true时,会将query也转为对象

 

2、url.format()用于将url对象转为字符串

我们将上面的url对象obj1转为url字符串
//使用url的format方法将url对象转为字符串
    var url_str1 = url.format(obj1)
    console.log(url_str1)
    //node输出结果如下:
    // http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa

可以看到,使用url.format()方法又将url对象转为了 url字符串

 

posted @ 2020-10-22 16:49  笑人  阅读(543)  评论(0编辑  收藏  举报