'How can I use the new URL API to get request details?
After following a tutorial on Node.js I tried to get the details of a request like so:
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.'));
This is working fine but I get a warning that url.parse()
is deprecated and instead I should use new URL()
API. But the problem is that with url.parse()
I can pass the req.url
as parameter whereas with new URL()
I have to pass a string as parameter, therefore I can't use req.url
to get the request details. Or is something I'm missing?
http
.createServer((req, res) => {
*let myUrl = new URL(req.url.toString());*
res.write(myUrl);
res.end();
})
.listen(3000, () => cl('Listening on port 3000.'));
If curl this URL curl http://localhost:3000/test?hello=world
, I get this error TypeError [ERR_INVALID_URL]: Invalid URL: /test?hello=world
Solution 1:[1]
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}`)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rafael Reis Ramos |