前两天因其他原素的耽误的 NodeJS 的继续学习,今天继续学习做笔记,现记录是 NodeJS 的 URL 分析。
NodeJS 的 URL 分析的主要功能是:将 URL 分解出下列参数对象,或者是将下列参数对象通过转换合并成正常使用的 URL 字符,下列的参数是否会都分析出来,这要取决于URL字符串是否有存在相对应的参数字符。不在的参数对象将自动默认给 null。
href: 显示完整URL
protocol:显示请求的协议
slashes:显示协议冒号后面是否带有双斜线
host:显示的是主机名加端口号
auth:登陆认证信息,这个是会在user:pass@host.com:8080中会出现,否则会显示 null
hostname:显示的是主机名
port:显示的是端口号,如果是80端口号,默认显示的是 null
pathname:显示的是路径地址
search:显示的是问号(?)之后,(#)之前的字符
path:显示的是包括路径名、文件名、参数在内的所有字符
query:显示的是 URL 传递的所有参数
hash:显示的是 URL 的 # 后字符
1、url.parse —— 将 URL 字符解析成 URL 对象,这个处理方法有三个参数分别是:
第一个参数是:URL 字符
第二个参数是:将解析出来的 query 以字符的形式输出,还是以对象的形式输出,如果设置为 true 将会以对象的形式输出,如果设置为 false 则会以字符形式输出,如不做设置将默认为 false。
第三个参数是:对不明协议的 URL 做解析,如果设置为 true 将会正确的解析,设置为 false 是不做规则性的解析,默认也是 false
① 只设置一个 URL 参数的示例:
url.parse('http://user:pass@host.com:8080/p/a/t/h?query=string#hash')
输出结果:
Url { 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 ,输出的结果
> url.parse('http://user:pass@host.com:8080/p/a/t/h?query=string#hash', true) Url { 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.parse('//blog.pkcms.cn/list/book', true)
③ 设置不设置第三个参数对不明协议处理结果的区别:
url.parse('//blog.pkcms.cn/list/book', true) Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '', query: {}, pathname: '//blog.pkcms.cn/list/book', path: '//blog.pkcms.cn/list/book', href: '//blog.pkcms.cn/list/book' } > url.parse('//blog.pkcms.cn/list/book', true, true) Url { protocol: null, slashes: true, auth: null, host: 'blog.pkcms.cn', port: null, hostname: 'blog.pkcms.cn', hash: null, search: '', query: {}, pathname: '/list/book', path: '/list/book', href: '//blog.pkcms.cn/list/book' }
2、url.format —— 将 url 对象转换成 url 字符串,这与 url.parse 的执行结果成相反关系,因此只要是通过 URL Parsing 转换出来的对象都能转换成原来的字符
3、url.resolve —— 为 URL 或 href 插入或替换原有的标签,下面是示例:
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'
转载请注明:隨習筆記 » NodeJS基础:URL 分析模块的使用