new URL() - WHATWG URL API(New URL()-WHATWG URL API)
问题描述
我正在处理节点,并尝试获取URL类的一个实例(因为这些方便的属性)。点赞:
const { URL } = require('url');
(...)
http.createServer((request,response) => {
let uri = new URL(request.url);
(...)
}
但失败,错误为
TypeError [ERR_INVALID_URL]: Invalid URL: /
这很有趣,因为
const url = require('url');
url.parse();
有效。所以我对它产生了好奇心。我知道后一种方法比较老。
我在本地开发,所以要发送请求,我在浏览器中使用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
推荐答案
正如Joshua Wise在Github(https://github.com/nodejs/node/issues/12682)上指出的那样,问题在于request.url不是一个绝对的URL。它可以用作路径或相对URL,但缺少主机和协议。
在API documentation之后,您可以通过提供一个基本URL作为第二个参数来构造一个有效的URL。这仍然很尴尬,因为该协议不容易从request.headers获得。我只是假设HTTP:
var baseURL = 'http://' + request.headers.host + '/';
var myURL = new URL(request.url, baseURL);
这显然不是一个理想的解决方案,但至少您可以利用查询字符串解析。例如,
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: '' }
这篇关于New URL()-WHATWG URL API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:New URL()-WHATWG URL API


- 从原点悬停时触发 translateY() 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01