美文网首页
node中的url常用方法解析

node中的url常用方法解析

作者: Macchiato_go | 来源:发表于2018-03-10 11:41 被阅读0次

url字符串是一个结构化的字符串,由好几个有意义部分组成。我们在工作中不可避免的会用到其中的某个部分,最原始的通过字符串截取和正则匹配的方法难免用起来会不太方便和美观,所以在我们的nodejs中提供了一个处理和解析url的模块url,该模块提供了一些实用的函数使我们解析起来更加的方便快捷,那接下里我们来分析一下它提供的常用的函数的用法

url模块提供了两套API来处理URLs:
一个是Node.js遗留的特有的API,

保留的原因:虽然Node.js遗留的特有的API并没有被弃用,但是保留的目的是用于向后兼容已有应用程序。因此新的应用程序请使用WHATWG API。

另一个则是通常使用在web浏览器中 实现了WHATWG URL Standard的API.该API是在node8.0.0中正式应用的

在浏览器中,WHATWG URL在全局总是可用的,而在Node.js中,任何情况下打开 或使用一个链接都必须事先引用'url'模块:require('url').URL

const url = require('url');
首先我们先来看看这个模块中都有哪些方法?
let http = require('http');
let url = require('url');
console.log(url);

// { Url: [Function: Url],
//     parse: [Function: urlParse],
//     resolve: [Function: urlResolve],
//     resolveObject: [Function: urlResolveObject],
//     format: [Function: urlFormat],
//     URL: [Function: URL],
//     URLSearchParams: [Function: URLSearchParams],
//     domainToASCII: [Function: domainToASCII],
//     domainToUnicode: [Function: domainToUnicode] }
接下来我们挨个来讲解上面这些方法的用法
let {parse, resolve, format, URL, URLSearchParams, domainToASCII, domainToUnicode} = require('url');
1、parse(urlStr,queryString,AnalysisHost)

Node.js遗留的特有的API
参数:

urlStr: 要解析的url地址
queryString: 解析出来的查询字符串还是查询对象,true是对象 false是字符串,例如:http://foo/bar?a=123, true的话 query: {a: 123}, false的话 query: 'a=123' 默认是false
AnalysisHost: 是否要解析出来host (即将//之后至下一个/之前的字符串),例如://foo/bar 会被解析为{host: 'foo', pathname: '/bar},否则{pathname: '//foo/bar'}.默认是false

作用:解析url,返回一个url属性对象

例如:

const myURLA =
    url.parse('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash', true);
console.log(myURLA);

// Url {
//     protocol: 'https:', // 协议
//         slashes: true,
//         auth: 'user:pass', // 用户名密码
//         host: 'sub.host.com:8080', // host主机名
//         port: '8080', // 端口号
//         hostname: 'sub.host.com', // 主机名不带端口号
//         hash: '#hash', // 哈希值
//         search: '?query=string',// 查询字符串
//         query: 'query=string', // 请求参数
//         pathname: '/p/a/t/h', // 路径名
//         path: '/p/a/t/h?query=string', // 带查询的路径名
//         href: 'https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash' // 原字符串本身
}

错误:

如果urlStr不是字符串将会抛出TypeError。

const myurl = url.parse({a:123});
TypeError: Parameter "url" must be a string, not object

如果auth属性存在但无法编码则抛出URIError。

2、resolve(from, to)

参数:

from: 解析时对应的基本的url
to:要解析的超链接url

作用:以一种 Web 浏览器解析超链接的方式把一个目标 URL 解析成相对于一个基础 URL。

例如:

const url = require('url');
url.resolve('/one/two/three', 'four');         // '/one/two/four'
url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
3、format(url,options)

参数:

url: 一个WHATWG URL对象
options:
1. auth: 如果序列化的URL字符串应该包含用户名和密码为true,否则为false。默认为true。
2. fragment: 如果序列化的URL字符串应该包含分段为true,否则为false。默认为true。即是不是需要包含哈希值
3. search: 如果序列化的URL字符串应该包含搜索查询为true,否则为false。默认为true。
4. unicode: true 如果出现在URL字符串主机元素里的Unicode字符应该被直接编码而不是使用Punycode编码为true,默认为false。
返回一个WHATWG URL对象的可自定义序列化的URL字符串表达。

虽然URL对象的toString()方法和href属性都可以返回URL的序列化的字符串。然而,两者都不可以被自定义。而url.format(URL[, options])方法允许输出的基本自定义。

例如:

const { URL } = require('url');
const myURL = new URL('https://a:b@你好你好?abc#foo');

console.log(myURL.href);
  // 输出 https://a:b@xn--6qqa088eba/?abc#foo

console.log(myURL.toString());
  // 输出 https://a:b@xn--6qqa088eba/?abc#foo

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
  // 输出 'https://你好你好/?abc'
4、new URL(input[, base])

浏览器兼容的 URL 类,根据 WHATWG URL 标准实现。

注意: 根据浏览器的约定,URL 对象的所有属性都是在类的原型上实现为getter和setter,而不是作为对象本身的数据属性。因此,与[遗留的urlObjects][]不同,在 URL 对象的任何属性(例如 delete myURL.protocol,delete myURL.pathname等)上使用 delete 关键字没有任何效果,但仍返回 true。

参数:

input: 解析的输入url
base: 如果“input”是相对url,则为要解析的基本url

作用:通过将input解析到base上创建一个新的URL对象。如果base是一个字符串,则解析方法与new URL(base)相同。

例如:

const { URL } = require('url');
const myURL = new URL('/foo', 'https://example.org/');
  // https://example.org/foo

如果input或base是无效URLs,将会抛出TypeError。请注意给定值将被强制转换为字符串。例如:

const { URL } = require('url');
const myURL = new URL({ toString: () => 'https://example.org/' });
  // https://example.org/

存在于input主机名中的Unicode字符将被使用Punycode算法自动转换为ASCII。

const { URL } = require('url');
const myURL = new URL('https://你好你好');
  // https://xn--6qqa088eba/
5.URLSearchParams

URLSearchParamsAPI接口提供对URLquery部分的读写权限。URLSearchParams类也能够与以下四个构造函数中的任意一个单独使用。

例如:

const { URL, URLSearchParams } = require('url');

const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// 输出 123

myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// 输出 https://example.org/?abc=123&abc=xyz

myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// 输出 https://example.org/?a=b

const newSearchParams = new URLSearchParams(myURL.searchParams);
// 上面的代码等同于
// const newSearchParams = new URLSearchParams(myURL.search);

newSearchParams.append('a', 'c');
console.log(myURL.href);
// 输出 https://example.org/?a=b
console.log(newSearchParams.toString());
// 输出 a=b&a=c

// newSearchParams.toString() 被隐式调用
myURL.search = newSearchParams;
console.log(myURL.href);
// 输出 https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// 输出 https://example.org/?a=b&a=c
6、domainToASCII(domain)

返回Punycode ASCII序列化的domain. 如果domain是无效域名,将返回空字符串。
它执行的是url.domainToUnicode()的逆运算。

const url = require('url');
console.log(url.domainToASCII('español.com'));
  // 输出 xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
  // 输出 xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
  // 输出空字符串
7. domainToUnicode(domain)

返回Unicode序列化的domain. 如果domain是无效域名,将返回空字符串。

它执行的是url.domainToASCII()的逆运算。

const url = require('url');
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
  // 输出 español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
  // 输出 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
  // 输出空字符串

相关文章

  • node中的url常用方法解析

    url字符串是一个结构化的字符串,由好几个有意义部分组成。我们在工作中不可避免的会用到其中的某个部分,最原始的通过...

  • nodejs基础四(横扫nodejsAPI)

    一.URL网址解析的好帮手(node API -- URL) url的方法1.parse:分析、解析eg: url...

  • NodeJs学习3--API

    url node下打印url 引入url模块 parse方法 将url解析成对象,parse方法原型: 可传递三个...

  • javascript将url解析为json格式

    方法一:最简单的方法,利用a标签来实现 得到的结果 方法二:通过nodejs的url模块解析URL需要用到Node...

  • formidable处理node.js的post请求

    前言 我们都知道在node.js中,我们最常用的请求方式是get和post。其中get请求和URL相关,通过解析U...

  • Web 应用大概都包含有什么内容

    《深入浅出 Node.js》阅读随笔 请求方法:get、post 、put、delete 等; Url 的路由解析...

  • 前端常用的三方库收集

    JavaScript node-url:解析url的工具codemirror:代码编辑器Monaco Editor...

  • NODE 构建Web应用

    构建web应用会遇到的问题 请求方法的判断 URL路径的解析 URL中查询字符串的解析 Cookie的解析 表单数...

  • Node中url模块的方法

    URL模块是NodeJS的核心模块之一,用于解析url字符串和url对象 1、url.parse(url_str[...

  • Node.js 学习url

    首先进入命令行 $ node >url 下面解析一个网址 parse :解析一个URL地址 ,生成对象 使用法...

网友评论

      本文标题:node中的url常用方法解析

      本文链接:https://www.haomeiwen.com/subject/wlivfftx.html