当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。