分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

url模块

发布时间:2023-09-06 01:28责任编辑:苏小强关键词:url

NodeJS之URL模块

  今天讲的是NodeJS里面的一个简单的小模块,即url模块;这个url模块要使用的话,需要先引入。若只是在命令行里比如cmd或git bash等使用url这个模块的话,是不需要require进来的。直接使用便可

  const这个关键字是ES6里面定义的常量,不可以改变。

1.const url = require("url");

  url总共提供了三个方法,分别是url.parse();  url.format();  url.resolve();

  1.url.parse(urlString[, parseQueryString[, slashesDenoteHost]])

  会返回一个解析后的对象,第一个参数为要解析的url地址,第二个参数为是否将query字符串解析成对象格式,第三个参数来控制在没有协议的情况下,是否解析域名等内容

  例子1:url.parse只传一个参数的情况

 ?url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash"); ?/* ?返回值: ?{ ???protocol: ‘http:‘, ???slashes: true, ???auth: ‘user:pass‘, ???host: ‘host.com:8080‘, ???port: ‘8080‘, ???hostname: ‘host.com‘, ???hash: ‘#hash‘, ???search: ‘?query=string‘, ???query: ‘query=string‘, ???pathname: ‘/p/a/t/h‘, ???path: ‘/p/a/t/h?query=string‘, ???href: ‘http://user:pass@host.com:8080/p/a/t/h?query=string#hash‘ ?} 没有设置第二个参数为true时,query属性为一个字符串类型*/

  例子2 : url.parse第二个参数为true的情况  

 url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash",true); ?/* ?返回值: ??{ ???protocol: ‘http:‘, ???slashes: true, ???auth: ‘user:pass‘, ???host: ‘host.com:8080‘, ???port: ‘8080‘, ???hostname: ‘host.com‘, ???hash: ‘#hash‘, ???search: ‘?query=string‘, ???query: { query: ‘string‘ }, ???pathname: ‘/p/a/t/h‘, ???path: ‘/p/a/t/h?query=string‘, ???href: ‘http://user:pass@host.com:8080/p/a/t/h?query=string#hash‘ ?} 返回的url对象中,query属性为一个对象 */

  

  2 url.format(urlObj) 

  将一个url解析后的对象还原成一个url地址
  参数:urlObj指一个url对象
  
url.format({ ???protocol:"http:", ???host:"182.163.0:60", ???port:"60"});/*返回值:‘http://182.163.0:60‘*/

  

  3.url.resolve(from, to)

  可以将我们两段url解析成一个url地址
  
url.resolve(‘http://www.baidu.com‘,‘/api/index.html‘);/*返回值:‘http://www.baidu.com/api/index.html‘*/

  url模块的三种方法就讲到这里了,不太全面的地方大家可以继续查阅其它资料哦。

url模块

原文地址:http://www.cnblogs.com/llc-url/p/7954370.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved