node.js URL module throws an error when parsing the URL directly from the Request object of the http server

697 views Asked by At

Node.js v18.15.0 Ubuntu 22.04 NPM 9.5.0

When creating the routing operations of my node.js http server, the WHATWG URL standard throws an error when I pass it the response.url directly.

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);

results in the following error:

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

I'm trying to move from the legacy API for the node.js URL module which works perfectly with this syntax and console logs the values as verification.

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
0

There are 0 answers