新的URL() - WHATWG URL API

Tho*_*lla 9 javascript node.js server

我正在搞乱节点,我正在尝试获取URL类的实例(因为那些方便的属性).喜欢:

const { URL } = require('url');
(...)
http.createServer((request,response) => {
    let uri = new URL(request.url);
    (...)
}
Run Code Online (Sandbox Code Playgroud)

但它失败了

TypeError [ERR_INVALID_URL]: Invalid URL: /
Run Code Online (Sandbox Code Playgroud)

这很有趣因为

const url = require('url');
url.parse();
Run Code Online (Sandbox Code Playgroud)

作品.所以我很好奇.我明白后面的方法比较旧.

我正在本地开发所以发送请求我在浏览器中使用localhost:8000.

如何使用该信息request实例化新的URL对象?

信息和我已经看过的东西:

node -v
v9.3.0

https://nodejs.org/api/url.html#url_class_url
https://stackoverflow.com/questions/44738065/uncaught-typeerror-url-is-not-a-constructor-using-whatwg-url-object-support-for
https://stackoverflow.com/questions/45047840/in-node-js-how-to-get-construct-url-string-from-whatwg-url-including-user-and-pa
https://stackoverflow.com/questions/47481784/does-url-parse-protect-against-in-a-url
https://stackoverflow.com/questions/17184791/node-js-url-parse-and-pathname-property
Run Code Online (Sandbox Code Playgroud)

小智 5

正如Joshua Wise在Github(https://github.com/nodejs/node/issues/12682)上指出的那样,问题在于request.url不是绝对URL。它可以用作路径或相对URL,但缺少主机和协议。

遵循API文档,您可以通过提供基本URL作为第二个参数来构造有效的URL。这仍然很尴尬,因为该协议不易从request.headers中获得。我只是假设使用HTTP:

var baseURL = 'http://' + request.headers.host + '/';
var myURL = new URL(request.url, baseURL);
Run Code Online (Sandbox Code Playgroud)

这显然不是理想的解决方案,但至少您可以利用查询字符串解析的优势。例如,

URL {
  href: 'http://localhost:8080/?key1=value1&key2=value2',
  origin: 'http://localhost:8080',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:8080',
  hostname: 'localhost',
  port: '8080',
  pathname: '/',
  search: '?key1=value1&key2=value2',
  searchParams: URLSearchParams { 'key1' => 'value1', 'key2' => 'value2' },
  hash: '' }
Run Code Online (Sandbox Code Playgroud)