node.js URL模块在直接从http服务器的Request对象解析URL时抛出错误

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

Node.js v18.15.0 Ubuntu 22.04 NPM 9.5.0

在我的 node.js http 服务器创建路由操作时,WHATWG URL 标准在我直接传递 response.url 时抛出错误。

const httpServer = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    const requestURL = new URL(req.url);
    const requestHostname = requestURL.hostname;
    const requestPathname = requestURL.pathname;
    const requestParams = requestURL.searchParams;
    console.log(requestPathname);

导致以下错误:

node:internal/url:566
  throw new ERR_INVALID_URL(input);
  ^

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:399:5)
    at URL.onParseError (node:internal/url:566:9)
    at new URL (node:internal/url:646:5)
    at Server.<anonymous> (/var/www/newsat11.live/index.js:26:24)
    at Server.emit (node:events:513:28)
    at parserOnIncoming (node:_http_server:1072:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) {
  input: '/',
  code: 'ERR_INVALID_URL'
}

Node.js v18.15.0

我正在尝试从 node.js URL 模块的旧版 API 迁移,该模块与此语法完美配合,控制台将值记录为验证。

const httpServer = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    const requestURL = new url.parse(req.url);
    const requestHostname = requestURL.hostname;
    const requestPathname = requestURL.pathname;
    const requestParams = requestURL.searchParams;
    console.log(requestPathname); // logs "/" as the pathname for localhost
node.js url module ubuntu-22.04 url-parsing
© www.soinside.com 2019 - 2024. All rights reserved.