nodejs_url模块
url.parse()
- 用于将url转换为对象形式:
const url = require('url');
var str = "https://www.tmooc.cn:3000/course/web.html?cname=js&price=5000";
var obj = url.parse(str);
console.log(obj);
// Url {
// protocol: 'https:',
// slashes: true,
// auth: null,
// host: 'www.tmooc.cn:3000',
// port: '3000',
// hostname: 'www.tmooc.cn',
// hash: null,
// search: '?cname=js&price=5000',
// query: 'cname=js&price=5000',
// pathname: '/course/web.html',
// path: '/course/web.html?cname=js&price=5000',
// href: 'https://www.tmooc.cn:3000/course/web.html?cname=js&price=5000'
// }
- 如果需要获取查询字符串有两种方法
1 对url.parse传入第二个参数true,其会将query的值转换为对象
var obj1 = url.parse(str, true);
console.log(obj1);
console.log(`obj1:${obj1.query.cname}`);//js
2 调用querystring模块对query的值进行转化
console.log(querystring.parse(obj.query).cname);//js
url.format
- 和url.parse相反的操作。将对象整合为完整的url地址。
url.resolve(from,to);
var a = url.resolve('/one/two/three', 'four') ,
b = url.resolve('http://example.com/', '/one'),
c = url.resolve('http://example.com/one', '/two');
console.log(a +","+ b +","+ c);
// /one/two/four,http://example.com/one,http://example.com/two