url.urlToHttpOptions(url)


  • url <URL> 要转换为选项对象的 WHATWG URL 对象。

    ¥url <URL> The WHATWG URL object to convert to an options object.

  • 返回:<Object> 选项对象

    ¥Returns: <Object> Options object

    • protocol <string> 要使用的协议。

      ¥protocol <string> Protocol to use.

    • hostname <string> 要向其触发请求的服务器的域名或 IP 地址。

      ¥hostname <string> A domain name or IP address of the server to issue the request to.

    • hash <string> 网址的片段部分。

      ¥hash <string> The fragment portion of the URL.

    • search <string> 网址的序列化的查询部分。

      ¥search <string> The serialized query portion of the URL.

    • pathname <string> 网址的路径部分。

      ¥pathname <string> The path portion of the URL.

    • path <string> 请求的路径。应包括查询字符串(如果有)。E.G.'/index.html?page=12'。当请求路径包含非法字符时抛出异常。目前,只有空格被拒绝,但将来可能会改变。

      ¥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> 序列化的网址。

      ¥href <string> The serialized URL.

    • port <number> 远程服务器的端口。

      ¥port <number> Port of remote server.

    • auth <string> 基本身份验证,即 'user:password' 计算授权标头。

      ¥auth <string> Basic authentication i.e. 'user:password' to compute an Authorization header.

该实用函数按照 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'
}
*/