url.protocol是url模块内的类URL的内置应用程序编程接口,用于获取和设置URL的协议部分。使用特殊协议之一解析URL时,url.protocol属性可以更改为另一个特殊协议,但不能更改为非特殊协议,反之亦然。
用法:
const url.protocol
返回值:它返回URL的协议部分。
以下示例说明了Node.js中url.protocol方法的使用:
范例1:
// Node program to demonstrate the
// url.protocol API as Setter
// Importing the module 'url'
const http = require('url');
// Creating and initializing myURL
const myURL = new URL('https://geeksforgeeks.org:80/foo#ram');
// Display href value of myURL before change
console.log("Before Change");
console.log(myURL.href);
// Assinging protocol portion
// using protocol
console.log();
myURL.protocol = 'http';
// Display href value of myURL after change
console.log("After Change");
console.log(myURL.href);
输出:
Before Change https://geeksforgeeks.org:80/foo#ram After Change http://geeksforgeeks.org/foo#ram
范例2:本示例将特殊协议更改为非特殊协议。
// Node program to demonstrate the
// url.protocol API as Setter
// Importing the module 'url'
const http = require('url');
// Creating and initializing myURL
const myURL = new URL('https://geeksforgeeks.org:80/foo#ram');
// Display href value of myURL before change
console.log("Before Change");
console.log(myURL.href);
// Assinging protocol portion
// with non special protocol
// using protocol
console.log();
myURL.protocol = 'xyz';
// Display href value of myURL after change
console.log("After Change");
console.log(myURL.href);
输出:
Before Change https://geeksforgeeks.org:80/foo#ram After Change https://geeksforgeeks.org:80/foo#ram
范例3:
// Node program to demonstrate the
// url.protocol API as Getter
// Importing the module 'url'
const http = require('url');
// Creating and initializing myURL
const myURL = new URL('https://geeksforgeeks.org:80/foo#ram');
// Getting the protocol portion
// using protocol
const protocol = myURL.protocol;
// Display hash value
console.log("Protocol of current url is:" + protocol);
输出:
Protocol of current url is:https:
注意:上面的程序将使用node myapp.js命令编译并运行。
参考: https://nodejs.org/api/url.html#url_url_protocol
相关用法
- Node.js URL.pathToFileURL用法及代码示例
- Node.js URL.fileURLToPath用法及代码示例
- Node.js URLSearchParams.has()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Node | URL.protocol API。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。