URL 类的 Node.js url.urlToHttpOptions() 方法接受一个 URL 对象,并将此 URL 对象转换为一个普通的选项对象,该对象包含 URL 中每个段的数据。
为了更好地理解 URL 中的段。假设序列化的 URL“https://user:password@site.com:80/pa/th?a=bc#footer”。
- “https:” 是协议段。
- “user:password”是身份验证段。
- “site.com”是主机名段。
- “80”是端口段。
- “/pa/th”是路径名段。
- “/pa/th?a=bc”是路径段。
- “a=bc”是搜索段。
- “#footer”是哈希段。
语法
以下是 URL 类的 NodeJS url.urlToHttpOptions() 方法的语法
url.urlToHttpOptions(url)
参数
- url:此参数包含一个 WHATWG URL 对象,该对象将转换为选项对象。
返回值
此方法将 WHATWG URL 对象转换为选项对象。
以下是返回的 options 对象中存在的属性
- protocol:指定 URL 的协议段。
- hostname:指定可能包含服务器的域名或 IP 地址的 URL 的主机名段。
- hash :指定 URL 的片段段。
- search:指定 URL 的序列化查询段。
- pathname:指定 URL 的路径名段。
- path:指定 URL 的路径段。如果输入URL中的路径段包含非法字符,则会抛出异常。
- href:指定序列化的 URL。
- port:指定 URL 的端口段。
- auth:指定 URL 的用户名和密码段。
如果我们将 URL 对象传递给 NodeJS url.urlToHttpOptions() 方法,它会将输入 URL 对象转换为指定 URL 中每个段的对象。
在以下示例中,我们尝试使用 NodeJS url.urlToHttpOptions() 方法将 URL 对象转换为选项对象。
const { urlToHttpOptions } = require('node:url');
const myURL = new URL("https://user:password@こんにちは:80/pa/th?a=bc#footer");
console.log(urlToHttpOptions(myURL));
输出
以下是上述程序的输出
internal/modules/cjs/loader.js:596
throw err;
^
Error: Cannot find module 'node:url'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
at Function.Module._load (internal/modules/cjs/loader.js:520:25)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/home/cg/root/63a2e36702387/main.js:1:92)
at Module._compile (internal/modules/cjs/loader.js:702:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
throw err;
^
Error: Cannot find module 'node:url'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
at Function.Module._load (internal/modules/cjs/loader.js:520:25)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/home/cg/root/63a2e36702387/main.js:1:92)
at Module._compile (internal/modules/cjs/loader.js:702:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
注意:为了获得准确的结果,最好在本地执行上述代码。
正如我们在输出中看到的,NodeJS urlToHttpOptions() 方法将输入 URL 对象转换为普通的选项对象。
{
protocol: 'https:',
hostname: 'xn--28j2a3ar1p',
hash: '#footer',
search: '?a=bc',
pathname: '/pa/th',
path: '/pa/th?a=bc',
href: 'https://user:password@xn--28j2a3ar1p:80/pa/th?a=bc#footer',
port: 80,
auth: 'user:password'
}
protocol: 'https:',
hostname: 'xn--28j2a3ar1p',
hash: '#footer',
search: '?a=bc',
pathname: '/pa/th',
path: '/pa/th?a=bc',
href: 'https://user:password@xn--28j2a3ar1p:80/pa/th?a=bc#footer',
port: 80,
auth: 'user:password'
}