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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。