当前位置: 首页 > 后端技术 > Node.js

Node中url模块的使用

时间:2023-04-03 14:25:53 Node.js

URL模块是NodeJS的核心模块之一。它用于解析url字符串和url对象。这个方法有两个参数,第一个参数是url字符串,第二个是boolean值,可以省略,表示是否将查询转化为对象url.parse(url_str)//注意下面的代码可以只能在节点运行中使用//定义一个url字符串varurl_str="http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa"//1,导入url模块varurl=require("url")//使用url.parse()方法将url字符串转为对象varobj=url.parse(url_str)console.log(obj)//在node中输出结果如下//Url{//protocol:'http:',//slashes:true,//auth:null,//host:'localhost:3000',//port:'3000',//hostname:'localhost',//哈希:'#aaa',//搜索:'?a=1&b=2&c=3',//查询:'a=1&b=2&c=3',//路径名:'/html/index.html',//路径:'/html/index.html?a=1&b=2&c=3',//href:'http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa'}可以看出,如果不写第二个参数时,默认为false,即不将查询转化为对象url.parse(url_str,true)varobj1=url.parse(url_str,true)缺点ole.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'},//路径名:'/html/index.html',//路径:'/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对象转成字符串varurl_str1=url.format(obj1)console.log(url_str1)//node的输出如下://http://localhost:3000/html/index.html?a=1&b=2&c=3#aaa可以看到url对象被转换了使用url.format()方法字符串转换为url字符