Nodejs教程13:URL模块
chencl1986 opened this issue · 0 comments
chencl1986 commented
阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。
url.parse
URL模块用于对URL的解析,常用的是url.parse方法。
假设有一个url为https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4,可以用url.parse方法进行解析。
示例代码:/lesson13/url.js
const url = require('url')
const str = 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4'
console.log(url.parse(str))
打印结果如下:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.google.com:8080',
port: '8080',
hostname: 'www.google.com',
hash: null,
search: '?x=1&y=2&y=3&y=4',
query: 'x=1&y=2&y=3&y=4',
pathname: '/a/b',
path: '/a/b?x=1&y=2&y=3&y=4',
href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4' }
可以看到url的信息如端口号、域名、query参数等都被解析出来了。
如果需要将query参数转为对象,则可以为url.parse函数的第二个参数传true,如console.log(url.parse(str, true)),打印结果如下:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.google.com:8080',
port: '8080',
hostname: 'www.google.com',
hash: null,
search: '?x=1&y=2&y=3&y=4',
query: [Object: null prototype] { x: '1', y: [ '2', '3', '4' ] },
pathname: '/a/b',
path: '/a/b?x=1&y=2&y=3&y=4',
href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4' }
同时可以看到y=2&y=3&y=4参数被解析为了y: [ '2', '3', '4' ]。
new URL()
除了用url.parse方法解析url,还可以通过构造函数URL,创建一个实例,其中带有解析后的数据。
实例有一个toString方法,可以将实例解析为字符串url。
示例代码:/lesson13/url.js
代码如下:
const { URL } = require('url')
const urlObj = new URL(str)
console.log(urlObj)
console.log(urlObj.toString())
打印结果为:
URL {
href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4',
origin: 'https://www.google.com:8080',
protocol: 'https:',
username: '',
password: '',
host: 'www.google.com:8080',
hostname: 'www.google.com',
port: '8080',
pathname: '/a/b',
search: '?x=1&y=2&y=3&y=4',
searchParams:
URLSearchParams { 'x' => '1', 'y' => '2', 'y' => '3', 'y' => '4' },
hash: '' }
https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4 // toString方法解析出的url