• Node.js Video Tutorials

NodeJS - url.password 屬性



URL 類 的這個 **NodeJS url.password 屬性** 允許你獲取和設定給定 URL 的密碼部分。如果輸入的 URL 無效,則此屬性將丟擲 TypeError。

語法

以下是 **NodeJS URL 類密碼屬性** 的語法

URL.password

引數

此屬性不接受任何引數。

返回值

此屬性允許設定和獲取給定 URL 的密碼段。

示例

如果我們將 URL 分配給 NodeJS url.password 屬性,它將只返回給定 URL 的密碼部分。

在下面的程式中,我們嘗試從輸入的 URL 獲取密碼段。

const url = require('url');

const myURL = new URL("https://xyz:pass@dot.com");
console.log("Password segment in the URL: " + myURL.password);

輸出

執行上述程式後,password 屬性將從提供的 URL 獲取密碼段。

Password segment in the URL: pass

示例

NodeJS password 屬性允許將密碼設定為給定 URL 中的密碼段。

在下面的程式中,我們嘗試將密碼設定為 URL 中的密碼部分。

const url = require('url');

const myURL = new URL("https://xyz:pass@dot.com");
console.log("Password segment in the URL: " + myURL.password);

myURL.password = "T$123";
console.log("After setting the password to the password segment in the URL");
console.log(myURL.href);

輸出

正如我們在下面的輸出中看到的,輸入的密碼已被分配到 URL 中的密碼段。

Password segment in the URL: pass
After setting the password to the password segment in the URL
https://xyz:T$123@dot.com/

示例

如果我們將不是有效 URL 型別的的值分配給 password 屬性,則 password 屬性將丟擲 TypeError。

在給定的程式中,我們分配了一個物件的例項而不是 URL 給 password 屬性。

const url = require('url');

const myURL = new URL({});
console.log("Password segment in the URL: " + myURL.password);

TypeError

正如我們在下面的輸出中看到的,password 屬性丟擲 TypeError,因為分配的 URL 無效。

node:internal/url:564
  throw new ERR_INVALID_URL(input);
  ^

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:387:5)
    at URL.onParseError (node:internal/url:564:9)
    at new URL (node:internal/url:640:5)
    at Object.<anonymous> (C:\Users\Lenovo\Desktop\JavaScript\nodefile.js:3:15)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  input: '[object Object]',
  code: 'ERR_INVALID_URL'
}
nodejs_url_module.htm
廣告
© . All rights reserved.