如何使用新的 URL API 获取请求详细信息?

How can I use the new URL API to get request details?

在学习了 Node.js 上的教程后,我尝试像这样获取请求的详细信息:

const url = require('url');

http
    .createServer((req, res) => {
        *let parsedUrl = url.parse(req.url, true);*
        
        res.write('---------->  ');
        res.write(parsedUrl.search);
        res.write(parsedUrl.search);
        re.write(parsedUrl.pathname);
        res.write('  <----------');
        res.end();
    })
    .listen(3000, () => cl('Listening on port 3000.'));

这工作正常,但我收到一条警告,提示 url.parse() 已弃用,我应该使用 new URL() API。但问题是,使用 url.parse() 我可以将 req.url 作为参数传递,而使用 new URL() 我必须将字符串作为参数传递,因此我不能使用 req.url获取请求详细信息。还是我遗漏了什么?

http
    .createServer((req, res) => {
        *let myUrl = new URL(req.url.toString());*
        
        res.write(myUrl);
        res.end();
    })
    .listen(3000, () => cl('Listening on port 3000.'));

如果 curl 这个 URL curl http://localhost:3000/test?hello=world,我得到这个错误 TypeError [ERR_INVALID_URL]: Invalid URL: /test?hello=world

import http from "node:http"
import { URL } from "node:url"

const PORT = 3000

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

server.listen(PORT, () => `Server is running on port ${PORT}`)