url.urlToHttpOptions(url)


  • url <URL> 要转换为选项对象的 WHATWG URL 对象。
  • 返回值: <Object> 选项对象
    • protocol <string> 要使用的协议。
    • hostname <string> 发出请求的服务器的域名或 IP 地址。
    • hash <string> URL 的片段部分。
    • search <string> URL 的序列化查询部分。
    • pathname <string> URL 的路径部分。
    • path <string> 请求路径。如果有查询字符串,应包含查询字符串。例如 '/index.html?page=12'。当请求路径包含非法字符时将抛出异常。目前只拒绝空格,但将来可能会有变化。
    • href <string> 序列化后的 URL。
    • port <number> 远程服务器的端口。
    • auth <string> 基本认证,例如 'user:password' 用于计算 Authorization 头。

此实用函数将 URL 对象转换为普通的选项对象,以符合 http.request()https.request() API 的预期。

【This utility function converts a URL object into an ordinary options object as expected by the http.request() and https.request() APIs.】

import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(urlToHttpOptions(myURL));
/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(urlToHttpOptions(myURL));
/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/