• Node.js Video Tutorials

NodeJS - url.hostname 屬性



URL 模組的 URL 類中的 **NodeJS url.hostname 屬性** 允許我們獲取和設定指定 URL 的主機名部分。

**NodeJS url.hostname 屬性** 類似於 NodeJS host 屬性,但 hostname 和 host 之間的主要區別在於 hostname 不包含埠段。如果為 hostname 屬性分配任何無效的主機名值,則將忽略這些值。

語法

以下是 **URL 類 NodeJS hostname 屬性** 的語法:

URL.hostname

引數

此屬性不接受任何引數。

返回值

此屬性允許獲取和設定指定 URL 的主機名部分。

以下示例演示了路徑模組中 Node.js URL.hostname 屬性的用法。

示例

使用 NodeJS URL.hostname 屬性,我們可以獲取提供的 URL 的主機名部分。

在以下示例中,我們嘗試獲取給定 URL 的主機名部分。

const url = require('url');

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

輸出

如下所示的輸出中,URL.hostname 屬性列印給定 URL 的主機名部分。

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

示例

我們無法使用 URL.hostname 屬性更改 URL 中主機名部分的主機名和埠段的值。

在下面的示例中,我們嘗試使用 URL.hostname 屬性修改給定 URL 中主機名部分的主機名和埠段。

const url = require('url');

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

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

輸出

如下所示的輸出中,URL.hostname 屬性對給定 URL 的主機名部分沒有任何更改。

Before changing the port: https://tutorialspoint.tw:100/index.htm
After changing hostname and the port: https://tutorialspoint.tw:100/index.htm

示例

我們可以使用 URL.host 屬性設定主機名部分的主機名和埠段。

在以下示例中,我們嘗試使用 URL.host 屬性更改給定 URL 中主機名部分的主機名和埠段。

const url = require('url');

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

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

輸出

如果我們編譯並執行上述程式,URL.host 屬性會對給定 URL 進行指定的修改。

Before changing the hostname and port: https://tutorialspoint.tw:100/index.htm
After changing the hostname and port: https://www.tutorialsssspoint.com:101/index.htm
nodejs_url_module.htm
廣告