From 85144201f5bba8fa936ffba704e3a6f689959a06 Mon Sep 17 00:00:00 2001 From: zhangyongsheng Date: Wed, 6 Jan 2021 16:10:28 +0800 Subject: [PATCH] url: expose urlToHttpOptions utility --- doc/api/url.md | 46 +++++++++++++++++++ lib/_http_client.js | 6 +-- lib/https.js | 6 +-- lib/internal/url.js | 4 +- lib/url.js | 6 ++- test/parallel/test-url-urltooptions.js | 37 +++++++++++++++ .../test-whatwg-url-custom-properties.js | 36 --------------- 7 files changed, 95 insertions(+), 46 deletions(-) create mode 100644 test/parallel/test-url-urltooptions.js diff --git a/doc/api/url.md b/doc/api/url.md index 3f44a984912876..3c73a96d74e518 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -1029,6 +1029,50 @@ new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) ``` +### `url.urlToHttpOptions(url)` + + +* `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. + +```js +const { urlToHttpOptions } = require('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' +} +*/ +``` + ## Legacy URL API