NodeJS - url.hostname 属性


URL 模块的 URL 类的 NodeJS url.hostname 属性允许我们获取和设置指定 URL 的主机名部分。

NodeJS url.hostname 属性看起来类似于 NodeJS host 属性,但 hostname 和 host 之间的主要区别在于主机名不包含端口段。如果为主机名分配了任何无效的主机名值,则将忽略主机名属性。

语法

以下是 URL 类的 NodeJS hostname 属性的语法


 URL.hostname

参数

此属性不接受任何参数。

返回值

此属性允许获取和设置指定 URL 的主机名部分。

以下示例演示了路径模块的 Node.js URL.hostname 属性的用法。

例

使用 NodeJS URL.hostname 属性,我们可以获取所提供 URL 的主机名部分。

在以下示例中,我们尝试获取给定 URL 的主机名部分。


const url = require('url');

const myURL = new URL('https://www.qikepu.com:100/index.htm');
console.log("The URL: " + myURL.href);
console.log("Hostname of the URL: " + myURL.hostname);

输出

正如我们在下面的输出中看到的,URL.hostname 属性打印给定 URL 的主机名部分。

The URL: https://www.qikepu.com:100/index.htm
Hostname of the URL: www.qikepu.com

例

我们不能使用 URL.hostname 属性更改 URL 中主机名部分的主机名和端口段的值。

在下面的示例中,我们尝试使用 URL.hostname 属性修改给定 URL 中主机名部分的主机名和端口段。


const url = require('url');

const myURL = new URL('https://www.qikepu.com:100/index.htm');
console.log("Before changing the port: " + myURL.href);

myURL.hostname = "www.ttttttttqikepu.com:101"
console.log("After changing hostname and the port: " + myURL.href);

输出

正如我们在下面的输出中看到的,URL.hostname 属性没有对给定 URL 的主机名部分进行任何更改。

Before changing the port: https://www.qikepu.com:100/index.htm
After changing hostname and the port: https://www.qikepu.com:100/index.htm

例

我们可以使用 URL.host 属性设置主机名和主机名部分的端口段。

在以下示例中,我们尝试使用 URL.host 属性更改给定 URL 中主机名部分的主机名和端口段。


const url = require('url');

const myURL = new URL('https://www.qikepu.com:100/index.htm');
console.log("Before changing the hostname and port: " + myURL.href);

myURL.host = "www.qikepusssspoint.com:101"
console.log("After changing the hostname and port: " + myURL.href);

输出

如果我们编译并运行上述程序,则 URL.host 属性将对给定的 URL 进行指定的修改。

Before changing the hostname and port: https://www.qikepu.com:100/index.htm
After changing the hostname and port: https://www.qikepusssspoint.com:101/index.htm