URL 字符串是包含多个段的结构化字符串。如果我们解析此 URL 字符串,则返回一个 URL 对象。返回的 URL 对象包含 URL 字符串中存在的段。
urlObject 的 NodeJS urlObject.auth 属性指定 URL 的身份验证段。它也被称为用户信息。URL 中身份验证段的格式为 {username}[:{password}]。
没有指定规则规定身份验证段的格式应采用相同的方式,[:{password}] 部分是可选的。
语法
以下是 NodeJS urlObject.auth 属性的语法
urlObject.auth
参数
此属性不接受任何参数。
返回值
此属性检索 URL 的用户名和密码段。
例如果提供的 URL 包含身份验证段,即 {username}[:{password}]格式,则 auth 属性将检索该段。
在以下示例中,我们尝试从提供的 URL 中获取身份验证段。
注意:要使用 auth 属性从 URL 获取 auth 段,我们首先需要使用 NodeJS url.parse() 方法解析 URL;否则,身份验证段未定义。
const url = require('url');
let address = 'https://username=Nikhil:password=TutPoint@www.qikepu.com#foo';
let result = url.parse(address, true);
console.log(result.auth);
输出
正如我们在下面的输出中看到的,NodeJS auth 属性从 URL 中检索了 auth 段。
username=Nikhil:password=TutPoint
例
如果我们不解析指定的 URL,则 auth 属性将未定义。
我们试图在不解析的情况下从提供的 URL 中获取身份验证段。
const url = require('url');
let address = 'https://username=Nikhil:password=TutPoint@www.qikepu.com#foo';
console.log(address.auth);
输出
正如我们在下面的输出中看到的,auth 属性是未定义的。
undefined
例
auth 段中的 [:{password}] 部分是可选的。
在以下示例中,提供的 URL 仅包含用户名。
const url = require('url');
let address = 'https://username=Nikhil@www.qikepu.com#foo';
let result = url.parse(address, true);
console.log(result.auth);
输出
以下是上述代码的输出
username=Nikhil
例
如果提供的 URL 不包含 auth 段,则 auth 属性将检索 null。
const url = require('url');
let address = 'https:www.qikepu.com';
let result = url.parse(address, true);
console.log(result.auth);
输出
正如我们在下面的输出中看到的,auth 属性为 null,因为 URL 中不涉及 auth 段。
null