📅  最后修改于: 2023-12-03 14:44:40.690000             🧑  作者: Mango
Node.js provides a built-in module called url
that allows developers to parse and manipulate URLs. One useful property of the url
module is the hostname
API. In this article, we will explore what this API is, how it works, and some examples of how it can be used.
The URL.hostname
property of the url
module is a read-only string that contains the domain name (or IP address) of the URL. It does not include the protocol, port number, or any path or query parameters.
Here is an example of how to use the URL()
constructor and the URL.hostname
property to get the hostname of a URL:
const url = new URL('https://www.example.com/path/to/page.html?foo=bar#baz');
console.log(url.hostname); // 'www.example.com'
The URL.hostname
property is computed from the host component of the URL, which is defined as follows:
host = hostname [ ":" port ]
hostname= *( domainlabel "." ) toplabel [ "." ]
domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
toplabel = alpha | alpha *( alphanum | "-" ) alphanum
In simpler terms, the hostname
can be a series of alphanumeric labels, separated by a dot (.) and ending with an optional port number, which is separated from the hostname by a colon (:).
The URL.hostname
property can be changed, but doing so will also change the URL.host
property, which includes the hostname and port number (if specified).
Here are some examples of how the URL.hostname
property can be used in practice:
You can verify if a string is a valid hostname by checking if it matches the URL.hostname
regular expression pattern:
const validHostname = 'www.example.com';
const invalidHostname = 'example-.com';
const isValid = (hostname) => {
const url = new URL(`https://${hostname}`);
return url.hostname === hostname;
};
console.log(isValid(validHostname)); // true
console.log(isValid(invalidHostname)); // false
You can use the URL.hostname
property to extract the domain name of a list of URLs:
const urls = [
'https://www.google.com/search?q=node.js',
'https://github.com/nodejs/node',
'https://stackoverflow.com/questions/tagged/node.js',
];
const domains = urls.map((url) => new URL(url).hostname);
console.log(domains);
// ['www.google.com', 'github.com', 'stackoverflow.com']
You can use the URL.hostname
property to check if a URL is from a list of allowed domains:
const allowedDomains = ['www.example.com', 'blog.example.com'];
const url = new URL('https://blog.example.com/article.html');
const isAllowed = allowedDomains.some((domain) => url.hostname.endsWith(domain));
console.log(isAllowed); // true
The URL.hostname
property of the url
module is a handy API for working with hostnames in Node.js. It allows you to extract the domain name from a URL, validate hostnames, parse lists of URLs, and filter URLs by domain. By leveraging the power of the url
module, you can make your Node.js code more robust and reliable.