📜  节点 | URL.hostname API

📅  最后修改于: 2022-05-13 01:56:57.077000             🧑  作者: Mango

节点 | URL.hostname API

url.hostname是类 URL的内置应用程序编程接口,带有 in url模块,用于获取和设置 URL 的主机名部分。 url.hosturl.hostname之间的主要区别是,url.hostname不包括端口。

句法:

const url.hostname

返回值:它获取和设置 URL 的主机名部分。
下面的程序说明了url.hostname方法的使用:
示例 1:

javascript
// node program to demonstrate the
// url.hostname API as Setter
  
//importing the module 'url'
const http = require('url');
  
// creating and initializing myURL
const myURL = new URL('https://example.com:80/foo#ram');
  
// Display href value of myURL before change
console.log("Before Change");
console.log(myURL.href);
  
// assigning hostname portion
// using hostname
console.log();
myURL.hostname = 'example.org';
  
// Display href value of myURL after change
console.log("After Change");
console.log(myURL.href);


javascript
// node program to demonstrate the
// url.hostname API as Getter
 
//importing the module 'url'
const http = require('url');
 
// creating and initializing myURL
const myURL = new URL('https://example.org/foo#ram');
 
// getting the hostname portion
// using hostname
const hostname = myURL.hostname;
 
// Display hostname value
console.log(hostname);


输出



示例 2:

javascript

// node program to demonstrate the
// url.hostname API as Getter
 
//importing the module 'url'
const http = require('url');
 
// creating and initializing myURL
const myURL = new URL('https://example.org/foo#ram');
 
// getting the hostname portion
// using hostname
const hostname = myURL.hostname;
 
// Display hostname value
console.log(hostname);

输出:

注意:上述程序将使用 node myapp.js 命令编译和运行。
参考:
https://nodejs.org/dist/latest-v10.x/docs/api/url.html#url_url_host