require('url').parse('someurl.com/page')
have been docs-only deprecated, and our strict linter is unhappy about it... I have tried to replace it in our code with what the internet suggests new URL('someurl.com/page')
which works in most cases.
However, we have examples where the url is a local image some/image.png
and that was working nicely with url.parse() and returns:
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'
}
But the suggested replacement new URL('some/image.png')
throws a type error...
TypeError [ERR_INVALID_URL] [ERR_INVALID_URL]: Invalid URL: /some/image.png
url.parse is doing some validation and accept local paths, but the new url constructor does not. What to do ?
encode() # The querystring. encode() function is an alias for querystring. stringify() .
This package has been deprecated The querystring API is considered Legacy.
The legacy url API ( url. parse() , url. format() , and url. resolve() ) have been docs-only deprecated.
const server = http.createServer((req, res) => {
const baseURL = req.protocol + '://' + req.headers.host + '/';
const reqUrl = new URL(req.url,baseURL);
console.log(reqUrl);
});
will give 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: ''
}
You can use the base parameter of the URL constructor. For example:
new URL('some/image-png', "https://dummyurl.com")
For more info, https://nodejs.org/api/url.html#url_constructor_new_url_input_base.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With