node Legacy url.parse 已弃用,用什么代替?

问题描述 投票:0回答:6

require('url').parse('someurl.com/page')
已被弃用,仅限文档,我们严格的 linter 对此不满意...我尝试在我们的代码中用互联网建议的
new URL('someurl.com/page')
替换它,这在大多数情况下都有效。

但是,我们有一些示例,其中 url 是本地图像

some/image.png
,并且与 url.parse() 配合得很好并返回:

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')
会引发类型错误...

类型错误 [ERR_INVALID_URL] [ERR_INVALID_URL]:无效的 URL: /一些/image.png

url.parse 正在进行一些验证并接受本地路径,但新的 url 构造函数不这样做。该怎么办?

javascript node.js url
6个回答
35
投票
const server = http.createServer((req, res) => {
   const baseURL =  req.protocol + '://' + req.headers.host + '/';
   const reqUrl = new URL(req.url,baseURL);
   console.log(reqUrl);
});

将给出 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: ''
}

17
投票

您可以使用 URL 构造函数的基本参数。例如:

new URL('some/image-png', "https://dummyurl.com")

有关更多信息,https://nodejs.org/api/url.html#url_constructor_new_url_input_base


8
投票

这是如何在不使用任何外部模块的情况下获取查询字符串参数

const http = require("http");

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}/`);

  const query = new URLSearchParams(url.search);
  console.log(query.entries());

  res.end("I am done");
});

server.listen(3000);

7
投票
const path = require("path");
const url = require("url");

const p = path.join("public", "images", "a.jpg");

console.log(p);                                     // public\images\a.jpg
console.log(new url.URL(p, "http://xxx").pathname); // /public/images/a.jpg

0
投票

Node v16.17.1

这对我有用:

const { URL } = require('url');

const url = new URL('https://somewebsite.com/params?x=x')

0
投票

只需使用

new URL
即可解析获取所有数据:

const server = http.createServer((req, res) => {
   const parsedUrl = new URL(req.url, `https://${req.headers.host}/`);
   console.log(parsedUrl);
});

并且

parsedUrl
将包含所有 URL 的数据:

{
  href: 'https://localhost:8000/test/',
  origin: 'https://localhost:8000',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'localhost:5000',
  hostname: 'localhost',
  port: '8000',
  pathname: '/test/',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

根据您的协议使用

http
https
前缀。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.