url.protocol 是 url 模塊中類 URL 的內置應用程序編程接口,用於獲取和設置 URL 的協議部分。當使用其中一種特殊協議解析 URL 時,url.protocol 屬性可以更改為另一種特殊協議,但不能更改為非特殊協議,反之亦然。
用法:
const url.protocol
返回值:它返回 URL 的協議部分。
下麵的示例說明了 Node.js 中 url.protocol 方法的使用:
示例 1:
Javascript
// 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);
// Assigning 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:本示例將特殊協議更改為非特殊協議。
Javascript
// 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);
// Assigning 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:
Javascript
// 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:
注意:上述程序將使用以下命令編譯並運行節點myapp.js命令。
參考: https://nodejs.org/api/url.html#url_url_protocol
相關用法
- Node.js URL.protocol用法及代碼示例
- Node.js URL.pathToFileURL用法及代碼示例
- Node.js URL.password用法及代碼示例
- Node.js URL.pathname用法及代碼示例
- Node.js URL.port用法及代碼示例
- Node.js URL.toJSON()用法及代碼示例
- Node.js URL.fileURLToPath用法及代碼示例
- Node.js URL.resolve(from,to)用法及代碼示例
- Node.js URL.format(urlObject)用法及代碼示例
- Node.js URL.format用法及代碼示例
- Node.js URL.hash用法及代碼示例
- Node.js URL.host用法及代碼示例
- Node.js URL.hostname用法及代碼示例
- Node.js URL.href用法及代碼示例
- Node.js URL.origin用法及代碼示例
- Node.js URL.search用法及代碼示例
- Node.js URL.username用法及代碼示例
- Node.js URL.searchParams用法及代碼示例
- Node.js URL.createObjectURL(blob)用法及代碼示例
- Node.js URLSearchParams.sort()用法及代碼示例
- Node.js URLSearchParams.set()用法及代碼示例
- Node.js URLSearchParams.toString()用法及代碼示例
- Node.js URLSearchParams.keys()用法及代碼示例
- Node.js URLSearchParams.getAll()用法及代碼示例
- Node.js URLSearchParams.forEach()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js URL.protocol API。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。