當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js new URL(input[, base])用法及代碼示例

new URL(input[, base])

  • input <string> 要解析的絕對或相對輸入 URL。如果input 是相對的,則需要base。如果input 是絕對的,則忽略base。如果input 不是字符串,則首先是converted to a string
  • base <string> 如果 input 不是絕對的,則要解析的基本 URL。如果base 不是字符串,則首先是converted to a string

通過解析相對於 baseinput 創建一個新的 URL 對象。如果 base 作為字符串傳遞,它將被解析為等同於 new URL(base)

const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo

URL 構造函數可作為全局對象的屬性進行訪問。也可以從內置的 url 模塊導入:

import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.console.log(URL === require('node:url').URL); // Prints 'true'.

如果 inputbase 不是有效的 URL,則會拋出 TypeError。請注意,將努力將給定的值強製轉換為字符串。例如:

const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/

input 的主機名中出現的 Unicode 字符將使用 Punycode 算法自動轉換為 ASCII。

const myURL = new URL('https://測試');
// https://xn--g6w251d/

此函數僅在 node 可執行文件在啟用 ICU 的情況下編譯時可用。如果不是,則域名原封不動地通過。

如果事先不知道 input 是否是絕對 URL 並且提供了 base,建議驗證 URL 對象的 origin 是否是預期的。

let myURL = new URL('http://Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https://Example.com/', 'https://example.org/');
// https://example.com/

myURL = new URL('foo://Example.com/', 'https://example.org/');
// foo://Example.com/

myURL = new URL('http:Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https:Example.com/', 'https://example.org/');
// https://example.org/Example.com/

myURL = new URL('foo:Example.com/', 'https://example.org/');
// foo:Example.com/

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 new URL(input[, base])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。