From 06585a92cdb9e03ded6aa0b4bac915c77addacde Mon Sep 17 00:00:00 2001 From: zhangyongsheng Date: Wed, 6 Jan 2021 16:10:28 +0800 Subject: [PATCH] url: expose urlToHttpOptions utility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/35960 Fixes: https://github.com/nodejs/node/issues/34349 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso --- 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 11b37a4f8369d2..dfc9583395b38a 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -1087,6 +1087,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