NodeJS - protocol 属性


URL 类的 NodeJS url.protocol 属性获取并设置指定 URL 的协议部分。如果分配了任何无效的 URL 协议值,则此属性将忽略它们。

语法

以下是 URL 类的 NodeJS protocol 属性的语法


 URL.protocol

参数

此属性不接受任何参数。

返回值

此属性获取和设置所提供 URL 的协议部分。

例

如果我们将一个完整的 URL 分配给 NodeJS url.protocol 属性,它将获得给定 URL 的协议部分。

在下面的以下示例中,我们尝试从输入 URL 中获取协议段中的值。


const http = require('url');

const myURL = new URL('https://www.qikepu.com');
console.log("The URL: " + myURL.href);

console.log("The protocol portion of the URL is: " + myURL.protocol);

输出

执行上述程序后,协议属性从提供的 URL 中获取协议段。

The URL: https://www.qikepu.com/
The protocol portion of the URL is: https:

例

我们可以从提供的 URL 为协议段设置任何有效的协议值。

在以下示例中,我们尝试为协议段设置一个值 (“wss”)。


const http = require('url');

const myURL = new URL('https://qikepu.com');
console.log("Before updating the protocol: " + myURL.href);

myURL.protocol = "wss";
console.log("Trying to update the protocol to - " + myURL.protocol);
console.log("After updating the protocol portion: " + myURL.href);

输出

正如我们在下面的输出中看到的,URL 的协议段被修改了。

Before updating the URL: https://qikepu.com/
Trying to update the protocol to - wss:
After updating the protocol portion: wss://qikepu.com/

例

如果协议部分中提供了任何无效的协议值,则协议属性将忽略它们。

在以下示例中,我们将在 protocol 属性中分配一个具有无效协议值的 URL。


const http = require('url');

const myURL = new URL('https://qikepu.com');
console.log("Before updating the protocol: " + myURL.href);

myURL.protocol = "wswwsss";
console.log("Trying to update the protocol to - " + "wswwsss");
console.log("After updating the protocol portion: " + myURL.href);

输出

正如我们在输出中看到的,协议段中的无效协议值将被忽略。

Before updating the protocol: https://qikepu.com/
Trying to update the protocol to - wswwsss
After updating the protocol portion: https://qikepu.com/