當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js URL.protocol用法及代碼示例

url.protocol

獲取和設置 URL 的協議部分。

const myURL = new URL('https://example.org');
console.log(myURL.protocol);
// Prints https:

myURL.protocol = 'ftp';
console.log(myURL.href);
// Prints ftp://example.org/

分配給 protocol 屬性的無效 URL 協議值將被忽略。

特別計劃#

曆史
版本變化
v15.0.0

方案"gopher" 不再特殊。

WHATWG URL Standard 認為一些 URL 協議方案在解析和序列化方麵是特殊的。當使用這些特殊協議之一解析 URL 時,url.protocol 屬性可能會更改為另一個特殊協議,但不能更改為非特殊協議,反之亦然。

例如,從 http 更改為 https 可以:

const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org

但是,從http 更改為假設的fish 協議並不是因為新協議並不特殊。

const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org

同樣,也不允許從非特殊協議更改為特殊協議:

const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org

根據 WHATWG URL 標準,特殊協議方案是 ftpfilehttphttpswswss

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 URL.protocol。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。