• Node.js Video Tutorials

NodeJS - protocol 屬性



NodeJS url.protocol 屬性是 URL 類的一個屬性,用於獲取和設定指定 URL 的協議部分。如果分配了任何無效的 URL 協議值,此屬性將忽略它們。

語法

以下是NodeJS URL 類 protocol 屬性的語法

URL.protocol

引數

此屬性不接受任何引數。

返回值

此屬性獲取並設定提供的 URL 的協議部分。

示例

如果我們將完整的 URL 分配給 NodeJS url.protocol 屬性,它將獲取給定 URL 的協議部分。

在下面的示例中,我們嘗試從輸入 URL 中獲取協議段的值。

const http = require('url');

const myURL = new URL('https://tutorialspoint.tw');
console.log("The URL: " + myURL.href);

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

輸出

執行上述程式後,protocol 屬性將從提供的 URL 中獲取協議段。

The URL: https://tutorialspoint.tw/
The protocol portion of the URL is: https:

示例

我們可以將任何有效的協議值設定為從提供的 URL 中獲取的協議段。

在下面的示例中,我們嘗試將值 (“wss”) 設定為協議段。

const http = require('url');

const myURL = new URL('https://tutorialspoint.tw');
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://tutorialspoint.tw/
Trying to update the protocol to - wss:
After updating the protocol portion: wss://tutorialspoint.tw/

示例

如果在協議部分提供了任何無效的協議值,protocol 屬性將忽略它們。

在下面的示例中,我們在 protocol 屬性中分配了一個帶有無效協議值的 URL。

const http = require('url');

const myURL = new URL('https://tutorialspoint.tw');
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://tutorialspoint.tw/
Trying to update the protocol to - wswwsss
After updating the protocol portion: https://tutorialspoint.tw/
nodejs_url_module.htm
廣告