Node.js URL.hostname API
url.hostname是类URL的内置应用程序编程接口,带有 in url模块,用于获取和设置 URL 的主机名部分。 url.host和url.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