URL 类的 NodeJS url.host 属性获取并设置 URL 的 host 部分。如果将任何无效的 host 值分配给 host 属性,则将忽略这些值。
Node.js URL 模块提供了多个用于 URL 解析和解析的实用程序。
语法
以下是 URL 类的 NodeJS host 属性的语法
URL.host
参数
此属性不接受任何参数。
返回值
此属性获取和设置所提供 URL 的 host 段。
例我们可以使用 NodeJS URL.host 属性来获取 URL 的 host 部分的值。
在以下示例中,我们尝试获取所提供 URL 的 host 部分。
const url = require('url');
const myURL = new URL('https://www.qikepu.com/index.htm');
console.log(myURL.href);
console.log("Host portion of the URL: " + myURL.host);
输出
执行上述程序后,myURL.host 属性在 URL 的 host 部分返回了值。
https://www.qikepu.com/index.htm
Host portion of the URL: www.qikepu.com
Host portion of the URL: www.qikepu.com
例
我们还可以使用 URL.host 属性设置 URL 的 host 部分的值。
在下面的程序中,我们尝试为给定 URL 的 host 部分设置一个新值。
const url = require('url');
const myURL = new URL('https://www.qikepu.com/index.htm');
console.log(myURL.href);
console.log("The current host portion in URL: " + myURL.host);
myURL.host = "www.tutorix.com";
console.log("After modifying the host portion to: " + myURL.host);
console.log(myURL.href);
输出
正如我们在下面的输出中看到的,myURL.host 修改了给定 URL 的 fragment 属性。
https://www.qikepu.com/index.htm
The current host portion in URL: www.qikepu.com
After modifying the host portion to: www.tutorix.com
https://www.tutorix.com/index.htm
The current host portion in URL: www.qikepu.com
After modifying the host portion to: www.tutorix.com
https://www.tutorix.com/index.htm