问题描述
require('url').parse('someurl.com/page')
已被弃用 docs-only,我们严格的 linter 对此不满意......我试图替换它在我们的代码中使用互联网建议的 new URL('someurl.com/page')
在大多数情况下有效.
require('url').parse('someurl.com/page')
have been docs-only deprecated, and our strict linter is unhappy about it... I have tried to replace it in our code with what the internet suggests new URL('someurl.com/page')
which works in most cases.
但是,我们有一些示例,其中 url 是本地图像 some/image.png
并且与 url.parse() 配合得很好并返回:
However, we have examples where the url is a local image some/image.png
and that was working nicely with url.parse() and returns:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/some/image.png',
path: '/some/image.png',
href: '/some/image.png'
}
但是建议的替换 new URL('some/image.png')
会引发类型错误...
But the suggested replacement new URL('some/image.png')
throws a type error...
类型错误 [ERR_INVALID_URL] [ERR_INVALID_URL]:无效的 URL:/some/image.png
url.parse 正在做一些验证并接受本地路径,但新的 url 构造函数没有.该怎么办?
url.parse is doing some validation and accept local paths, but the new url constructor does not. What to do ?
推荐答案
const server = http.createServer((req, res) => {
const baseURL = req.protocol + '://' + req.headers.host + '/';
const reqUrl = new URL(req.url,baseURL);
console.log(reqUrl);
});
会给 reqUrl :
will give reqUrl :
URL {
href: 'http://127.0.0.1:3000/favicon.ico',
origin: 'http://127.0.0.1:3000',
protocol: 'http:',
username: '',
password: '',
host: '127.0.0.1:3000',
hostname: '127.0.0.1',
port: '3000',
pathname: '/favicon.ico',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
这篇关于不推荐使用节点旧版 url.parse,改用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!