url.urlToHttpOptions(url)


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

该实用函数按照 http.request()https.request() API 的预期将网址对象转换为普通选项对象。

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'
}
*/
  • url <URL> The WHATWG URL object to convert to an options object.
  • Returns: <Object> Options object
    • protocol <string> Protocol to use.
    • hostname <string> A domain name or IP address of the server to issue the request to.
    • hash <string> The fragment portion of the URL.
    • search <string> The serialized query portion of the URL.
    • pathname <string> The path portion of the URL.
    • path <string> Request path. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.
    • href <string> The serialized URL.
    • port <number> Port of remote server.
    • auth <string> Basic authentication i.e. 'user:password' to compute an Authorization header.

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'
}
*/