NodeJS - url.password 属性


URL 类的这个 NodeJS url.password 属性允许您获取和设置给定 URL 的密码部分。如果输入 URL 不是有效的 URL,则此属性将引发 TypeError。

语法

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


 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/

例

如果我们为 password 属性分配一个不是有效 URL 类型的值,则 password 属性将抛出 TypeError。

在给定的程序中,我们将对象的实例而不是 URL 分配给 password 属性。


const url = require('url');

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

类型错误

正如我们在下面的输出中看到的,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'
}