Node.js v26.0.0 說明文件
- Node.js v26.0.0
- 目錄
- URL
- URL 字串與 URL 物件
- WHATWG URL API
- 類別:
URL - 類別:
URLPattern - 類別:
URLSearchParamsnew URLSearchParams()new URLSearchParams(string)new URLSearchParams(obj)new URLSearchParams(iterable)urlSearchParams.append(name, value)urlSearchParams.delete(name[, value])urlSearchParams.entries()urlSearchParams.forEach(fn[, thisArg])urlSearchParams.get(name)urlSearchParams.getAll(name)urlSearchParams.has(name[, value])urlSearchParams.keys()urlSearchParams.set(name, value)urlSearchParams.sizeurlSearchParams.sort()urlSearchParams.toString()urlSearchParams.values()urlSearchParams[Symbol.iterator]()
url.domainToASCII(domain)url.domainToUnicode(domain)url.fileURLToPath(url[, options])url.fileURLToPathBuffer(url[, options])url.format(URL[, options])url.pathToFileURL(path[, options])url.urlToHttpOptions(url)
- 類別:
- 舊版 URL API
- URL 中的百分比編碼 (Percent-encoding)
- URL
- 索引
- 關於此說明文件
- 用法與範例
- 斷言測試
- 非同步內容追蹤
- Async hooks
- Buffer
- C++ 擴充套件
- 使用 Node-API 的 C/C++ 擴充套件
- C++ 嵌入器 API
- 子程序
- 叢集
- 命令列選項
- Console
- Crypto
- 除錯器
- 棄用的 API
- Diagnostics Channel
- DNS
- 網域 (Domain)
- 環境變數
- 錯誤
- 事件
- 檔案系統
- 全域變數
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:moduleAPI - 模組:套件
- 模組:TypeScript
- Net
- Iterable Streams API
- OS
- Path
- 效能勾子 (Performance hooks)
- 權限
- 程序
- Punycode
- 查詢字串
- Readline
- REPL
- 報告
- 單一可執行應用程式
- SQLite
- Stream
- 字串解碼器
- 測試執行器
- 計時器
- TLS/SSL
- 追蹤事件
- TTY
- UDP/資料報
- URL
- 公用工具
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- 工作執行緒
- Zlib
- Zlib 可反覆運算壓縮
- 其他版本
- 選項
URL#
穩定度:2 - 穩定
node:url 模組提供用於 URL 解析與處理的公用程式。可以透過以下方式存取:
import url from 'node:url';const url = require('node:url');
URL 字串與 URL 物件#
URL 字串是一個結構化字串,包含多個具有意義的組成部分。解析後會返回一個 URL 物件,其中包含這些組成部分的屬性。
node:url 模組提供兩種用於處理 URL 的 API:一種是 Node.js 特有的舊版 (legacy) API,另一種則是實作了與網頁瀏覽器相同的 WHATWG URL 標準 的新版 API。
下方提供了 WHATWG API 與舊版 API 的比較。在 URL 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash' 之上,顯示的是舊版 url.parse() 返回物件的屬性。之下則是 WHATWG URL 物件的屬性。
WHATWG URL 的 origin 屬性包含 protocol 與 host,但不包含 username 或 password。
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ href │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │ │ auth │ host │ path │ hash │
│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ │ │ ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
│ │ │ │ │ hostname │ port │ │ │ │
│ │ │ │ ├─────────────────┴──────┤ │ │ │
│ protocol │ │ username │ password │ host │ │ │ │
├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
│ origin │ │ origin │ pathname │ search │ hash │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│ href │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
使用 WHATWG API 解析 URL 字串
const myURL =
new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
使用舊版 API 解析 URL 字串
import url from 'node:url'; const myURL = url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');const url = require('node:url'); const myURL = url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
從組成部分建構 URL 並取得建構後的字串#
可以使用屬性設定器 (property setters) 或模板字串 (template literal string) 從組成部分建構 WHATWG URL
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
const myURL = new URL(`https://example.org${pathname}${search}${hash}`);
若要取得建構後的 URL 字串,請使用 href 屬性存取器
console.log(myURL.href);
WHATWG URL API#
類別:URL#
與瀏覽器相容的 URL 類別,根據 WHATWG URL 標準實作。解析後的 URL 範例 可以在標準文件本身中找到。URL 類別也可在全域物件上使用。
根據瀏覽器慣例,URL 物件的所有屬性都是在類別原型 (class prototype) 上作為 getter 和 setter 實作,而不是作為物件本身的資料屬性。因此,與 舊版 urlObject 不同,對 URL 物件的任何屬性使用 delete 關鍵字(例如 delete myURL.protocol、delete myURL.pathname 等)都沒有效果,但仍會返回 true。
new URL(input[, base])#
input<string>要解析的絕對或相對輸入 URL。如果input是相對路徑,則需要base。如果input是絕對路徑,則忽略base。如果input不是字串,會先被 轉換為字串。base<string>如果input不是絕對路徑,則作為解析基準的基準 URL。如果base不是字串,會先被 轉換為字串。
藉由相對於 base 解析 input 來建立新的 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'.
如果 input 或 base 不是有效的 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/
在事先不知道 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/
url.hash#
- 類型:
<string>
取得並設定 URL 的片段 (fragment) 部分。
const myURL = new URL('https://example.org/foo#bar');
console.log(myURL.hash);
// Prints #bar
myURL.hash = 'baz';
console.log(myURL.href);
// Prints https://example.org/foo#baz
包含在指派給 hash 屬性值中的無效 URL 字元會被 百分比編碼。選擇哪些字元進行百分比編碼可能與 url.parse() 和 url.format() 方法產生的結果略有不同。
url.host#
- 類型:
<string>
取得並設定 URL 的主機 (host) 部分。
const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);
// Prints example.org:81
myURL.host = 'example.com:82';
console.log(myURL.href);
// Prints https://example.com:82/foo
指派給 host 屬性的無效主機值將被忽略。
url.hostname#
- 類型:
<string>
取得並設定 URL 的主機名稱 (host name) 部分。url.host 和 url.hostname 之間的主要區別在於 url.hostname 不 包含連接埠。
const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
// Prints example.org
// Setting the hostname does not change the port
myURL.hostname = 'example.com';
console.log(myURL.href);
// Prints https://example.com:81/foo
// Use myURL.host to change the hostname and port
myURL.host = 'example.org:82';
console.log(myURL.href);
// Prints https://example.org:82/foo
指派給 hostname 屬性的無效主機名稱值將被忽略。
url.href#
- 類型:
<string>
取得並設定序列化後的 URL。
const myURL = new URL('https://example.org/foo');
console.log(myURL.href);
// Prints https://example.org/foo
myURL.href = 'https://example.com/bar';
console.log(myURL.href);
// Prints https://example.com/bar
取得 href 屬性的值等同於呼叫 url.toString()。
將此屬性的值設定為新值等同於使用 new URL(value) 建立一個新的 URL 物件。URL 物件的每個屬性都將被修改。
如果指派給 href 屬性的值不是有效的 URL,將拋出 TypeError。
url.origin#
- 類型:
<string>
取得 URL 來源 (origin) 的唯讀序列化字串。
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org
const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d
console.log(idnURL.hostname);
// Prints xn--g6w251d
url.password#
- 類型:
<string>
取得並設定 URL 的密碼部分。
const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);
// Prints xyz
myURL.password = '123';
console.log(myURL.href);
// Prints https://abc:123@example.com/
包含在指派給 password 屬性值中的無效 URL 字元會被 百分比編碼。選擇哪些字元進行百分比編碼可能與 url.parse() 和 url.format() 方法產生的結果略有不同。
url.pathname#
- 類型:
<string>
取得並設定 URL 的路徑部分。
const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz
myURL.pathname = '/abcdef';
console.log(myURL.href);
// Prints https://example.org/abcdef?123
包含在指派給 pathname 屬性值中的無效 URL 字元會被 百分比編碼。選擇哪些字元進行百分比編碼可能與 url.parse() 和 url.format() 方法產生的結果略有不同。
url.port#
- 類型:
<string>
取得並設定 URL 的連接埠部分。
連接埠值可以是一個數字或一個包含 0 到 65535(含)範圍內數字的字串。將值設定為 URL 物件給定 protocol 的預設連接埠,將導致 port 值變成空字串 ('')。
連接埠值可以是空字串,在這種情況下連接埠取決於協定/方案:
| 協定 | 通訊埠 (port) |
|---|---|
| "ftp" | 21 |
| "file" | |
| "http" | 80 |
| "https" | 443 |
| "ws" | 80 |
| "wss" | 443 |
在為連接埠指派值時,該值將首先使用 .toString() 轉換為字串。
如果該字串無效但以數字開頭,則將開頭的數字指派給 port。如果數字超出上述範圍,則會被忽略。
const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// Prints 8888
// Default ports are automatically transformed to the empty string
// (HTTPS protocol's default port is 443)
myURL.port = '443';
console.log(myURL.port);
// Prints the empty string
console.log(myURL.href);
// Prints https://example.org/
myURL.port = 1234;
console.log(myURL.port);
// Prints 1234
console.log(myURL.href);
// Prints https://example.org:1234/
// Completely invalid port strings are ignored
myURL.port = 'abcd';
console.log(myURL.port);
// Prints 1234
// Leading numbers are treated as a port number
myURL.port = '5678abcd';
console.log(myURL.port);
// Prints 5678
// Non-integers are truncated
myURL.port = 1234.5678;
console.log(myURL.port);
// Prints 1234
// Out-of-range numbers which are not represented in scientific notation
// will be ignored.
myURL.port = 1e10; // 10000000000, will be range-checked as described below
console.log(myURL.port);
// Prints 1234
包含小數點的數字,例如浮點數或科學記號數字,也不例外。到小數點為止的開頭數字將被設定為 URL 的連接埠(假設它們有效):
myURL.port = 4.567e21;
console.log(myURL.port);
// Prints 4 (because it is the leading number in the string '4.567e21')
url.protocol#
- 類型:
<string>
取得並設定 URL 的協定部分。
const myURL = new URL('https://example.org');
console.log(myURL.protocol);
// Prints https:
myURL.protocol = 'ftp';
console.log(myURL.href);
// Prints ftp://example.org/
指派給 protocol 屬性的無效 URL 協定值將被忽略。
特殊協定方案#
WHATWG URL 標準 將少數 URL 協定方案視為解析和序列化方面的 特殊 方案。當使用這些特殊協定之一解析 URL 時,url.protocol 屬性可以更改為另一個特殊協定,但不能更改為非特殊協定,反之亦然。
例如,從 http 更改為 https 是可行的:
const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org/
然而,從 http 更改為假設的 fish 協定是不行的,因為新協定不是特殊協定。
const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org/
同樣地,從非特殊協定更改為特殊協定也是不允許的:
const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org
根據 WHATWG URL 標準,特殊協定方案包括 ftp、file、http、https、ws 和 wss。
url.search#
- 類型:
<string>
取得並設定 URL 序列化後的查詢 (query) 部分。
const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
// Prints ?123
myURL.search = 'abc=xyz';
console.log(myURL.href);
// Prints https://example.org/abc?abc=xyz
出現在指派給 search 屬性值中的任何無效 URL 字元都將被 百分比編碼。選擇哪些字元進行百分比編碼可能與 url.parse() 和 url.format() 方法產生的結果略有不同。
url.searchParams#
取得代表 URL 查詢參數的 URLSearchParams 物件。此屬性為唯讀,但它提供的 URLSearchParams 物件可用於變更 URL 實例;若要替換 URL 的全部查詢參數,請使用 url.search 設定器。詳情請參閱 URLSearchParams 說明文件。
使用 .searchParams 修改 URL 時請小心,因為根據 WHATWG 規範,URLSearchParams 物件使用不同的規則來決定哪些字元需要百分比編碼。例如,URL 物件不會對 ASCII 波浪號 (~) 字元進行百分比編碼,而 URLSearchParams 則一律會對其進行編碼:
const myURL = new URL('https://example.org/abc?foo=~bar');
console.log(myURL.search); // prints ?foo=~bar
// Modify the URL via searchParams...
myURL.searchParams.sort();
console.log(myURL.search); // prints ?foo=%7Ebar
url.username#
- 類型:
<string>
取得並設定 URL 的使用者名稱部分。
const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
// Prints abc
myURL.username = '123';
console.log(myURL.href);
// Prints https://123:xyz@example.com/
出現在指派給 username 屬性值中的任何無效 URL 字元都將被 百分比編碼。選擇哪些字元進行百分比編碼可能與 url.parse() 和 url.format() 方法產生的結果略有不同。
url.toString()#
- 傳回:
<string>
URL 物件上的 toString() 方法返回序列化後的 URL。返回的值等同於 url.href 和 url.toJSON() 的值。
url.toJSON()#
- 傳回:
<string>
URL 物件上的 toJSON() 方法返回序列化後的 URL。返回的值等同於 url.href 和 url.toString() 的值。
當 URL 物件使用 JSON.stringify() 進行序列化時,會自動呼叫此方法。
const myURLs = [
new URL('https://www.example.com'),
new URL('https://test.example.org'),
];
console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"]
URL.createObjectURL(blob)#
建立一個代表給定 <Blob> 物件的 'blob:nodedata:...' URL 字串,稍後可用於檢索該 Blob。
const {
Blob,
resolveObjectURL,
} = require('node:buffer');
const blob = new Blob(['hello']);
const id = URL.createObjectURL(blob);
// later...
const otherBlob = resolveObjectURL(id);
console.log(otherBlob.size);
由註冊的 <Blob> 儲存的資料將保留在記憶體中,直到呼叫 URL.revokeObjectURL() 將其移除。
Blob 物件在當前執行緒內註冊。如果使用工作執行緒 (Worker Threads),在一個 Worker 內註冊的 Blob 物件將不適用於其他 Worker 或主執行緒。
URL.revokeObjectURL(id)#
id<string>由先前呼叫URL.createObjectURL()回傳的'blob:nodedata:...URL 字串。
移除由給定 ID 識別的儲存 <Blob>。嘗試撤銷未註冊的 ID 將靜默失敗。
URL.canParse(input[, base])#
input<string>要解析的絕對或相對輸入 URL。如果input是相對路徑,則需要base。如果input是絕對路徑,則忽略base。如果input不是字串,會先被 轉換為字串。base<string>如果input不是絕對路徑,則作為解析基準的基準 URL。如果base不是字串,會先被 轉換為字串。- 傳回:
<boolean>
檢查相對於 base 的 input 是否可以解析為 URL。
const isValid = URL.canParse('/foo', 'https://example.org/'); // true
const isNotValid = URL.canParse('/foo'); // false
URL.parse(input[, base])#
input<string>要解析的絕對或相對輸入 URL。如果input是相對路徑,則需要base。如果input是絕對路徑,則忽略base。如果input不是字串,會先被 轉換為字串。base<string>如果input不是絕對路徑,則作為解析基準的基準 URL。如果base不是字串,會先被 轉換為字串。- 返回:
<URL>|<null>
將字串解析為 URL。如果提供了 base,它將作為解析非絕對路徑 input URL 的基準 URL。如果參數無法解析為有效的 URL,則返回 null。
類別:URLPattern#
穩定性:1 - 實驗性
URLPattern API 提供了一個介面,用於根據模式比對 URL 或 URL 的各部分。
const myPattern = new URLPattern('https://nodejs.com.tw/docs/latest/api/*.html');
console.log(myPattern.exec('https://nodejs.com.tw/docs/latest/api/dns.html'));
// Prints:
// {
// "hash": { "groups": { "0": "" }, "input": "" },
// "hostname": { "groups": {}, "input": "nodejs.org" },
// "inputs": [
// "https://nodejs.com.tw/docs/latest/api/dns.html"
// ],
// "password": { "groups": { "0": "" }, "input": "" },
// "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },
// "port": { "groups": {}, "input": "" },
// "protocol": { "groups": {}, "input": "https" },
// "search": { "groups": { "0": "" }, "input": "" },
// "username": { "groups": { "0": "" }, "input": "" }
// }
console.log(myPattern.test('https://nodejs.com.tw/docs/latest/api/dns.html'));
// Prints: true
new URLPattern()#
實例化一個新的空 URLPattern 物件。
new URLPattern(string[, baseURL][, options])#
string<string>一個 URL 字串baseURL<string>|<undefined>一個基準 URL 字串options<Object>選項
將 string 解析為 URL,並用其實例化一個新的 URLPattern 物件。
如果未指定 baseURL,則預設為 undefined。
選項可以具有 ignoreCase 布林屬性,如果設定為 true,則啟用不區分大小寫的比對。
建構函式可能會拋出 TypeError 以指示解析失敗。
new URLPattern(obj[, baseURL][, options])#
obj<Object>輸入模式baseURL<string>|<undefined>一個基準 URL 字串options<Object>選項
將 Object 解析為輸入模式,並用其實例化一個新的 URLPattern 物件。物件成員可以是 protocol、username、password、hostname、port、pathname、search、hash 或 baseURL 中的任何一個。
如果未指定 baseURL,則預設為 undefined。
選項可以具有 ignoreCase 布林屬性,如果設定為 true,則啟用不區分大小寫的比對。
建構函式可能會拋出 TypeError 以指示解析失敗。
urlPattern.exec(input[, baseURL])#
input<string>|<Object>一個 URL 或 URL 組成部分baseURL<string>|<undefined>一個基準 URL 字串
輸入可以是字串或提供個別 URL 組成部分的物件。物件成員可以是 protocol、username、password、hostname、port、pathname、search、hash 或 baseURL 中的任何一個。
如果未指定 baseURL,則預設為 undefined。
返回一個帶有 inputs 鍵的物件,該鍵包含傳遞到函數中的參數陣列,以及 URL 組成部分的鍵,其中包含比對到的輸入和比對到的群組。
const myPattern = new URLPattern('https://nodejs.com.tw/docs/latest/api/*.html');
console.log(myPattern.exec('https://nodejs.com.tw/docs/latest/api/dns.html'));
// Prints:
// {
// "hash": { "groups": { "0": "" }, "input": "" },
// "hostname": { "groups": {}, "input": "nodejs.org" },
// "inputs": [
// "https://nodejs.com.tw/docs/latest/api/dns.html"
// ],
// "password": { "groups": { "0": "" }, "input": "" },
// "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },
// "port": { "groups": {}, "input": "" },
// "protocol": { "groups": {}, "input": "https" },
// "search": { "groups": { "0": "" }, "input": "" },
// "username": { "groups": { "0": "" }, "input": "" }
// }
urlPattern.test(input[, baseURL])#
input<string>|<Object>一個 URL 或 URL 組成部分baseURL<string>|<undefined>一個基準 URL 字串
輸入可以是字串或提供個別 URL 組成部分的物件。物件成員可以是 protocol、username、password、hostname、port、pathname、search、hash 或 baseURL 中的任何一個。
如果未指定 baseURL,則預設為 undefined。
返回一個布林值,指示輸入是否與當前模式比對。
const myPattern = new URLPattern('https://nodejs.com.tw/docs/latest/api/*.html');
console.log(myPattern.test('https://nodejs.com.tw/docs/latest/api/dns.html'));
// Prints: true
類別:URLSearchParams#
URLSearchParams API 提供對 URL 查詢部分的讀寫存取。URLSearchParams 類別也可以使用以下四個建構函式之一獨立使用。URLSearchParams 類別也可在全域物件上使用。
WHATWG URLSearchParams 介面和 querystring 模組具有類似的目的,但 querystring 模組的目的更通用,因為它允許自訂分隔字元(& 和 =)。另一方面,此 API 是純粹為 URL 查詢字串設計的。
const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Prints 123
myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// Prints https://example.org/?abc=123&abc=xyz
myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// Prints https://example.org/?a=b
const newSearchParams = new URLSearchParams(myURL.searchParams);
// The above is equivalent to
// const newSearchParams = new URLSearchParams(myURL.search);
newSearchParams.append('a', 'c');
console.log(myURL.href);
// Prints https://example.org/?a=b
console.log(newSearchParams.toString());
// Prints a=b&a=c
// newSearchParams.toString() is implicitly called
myURL.search = newSearchParams;
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c
new URLSearchParams()#
實例化一個新的空 URLSearchParams 物件。
new URLSearchParams(string)#
string<string>一個查詢字串
將 string 解析為查詢字串,並用其實例化一個新的 URLSearchParams 物件。如果存在開頭的 '?',它將被忽略。
let params;
params = new URLSearchParams('user=abc&query=xyz');
console.log(params.get('user'));
// Prints 'abc'
console.log(params.toString());
// Prints 'user=abc&query=xyz'
params = new URLSearchParams('?user=abc&query=xyz');
console.log(params.toString());
// Prints 'user=abc&query=xyz'
new URLSearchParams(obj)#
obj<Object>代表鍵值對集合的物件
使用查詢雜湊表 (hash map) 實例化一個新的 URLSearchParams 物件。obj 每個屬性的鍵和值一律會被強制轉換為字串。
與 querystring 模組不同,不允許使用陣列值形式的重複鍵。陣列將使用 array.toString() 轉換為字串,這只是簡單地用逗號連接所有陣列元素。
const params = new URLSearchParams({
user: 'abc',
query: ['first', 'second'],
});
console.log(params.getAll('query'));
// Prints [ 'first,second' ]
console.log(params.toString());
// Prints 'user=abc&query=first%2Csecond'
new URLSearchParams(iterable)#
iterable<Iterable>一個其元素為鍵值對的可迭代物件
以類似於 <Map> 建構函式的方式,使用可迭代映射 (iterable map) 實例化一個新的 URLSearchParams 物件。iterable 可以是 Array 或任何可迭代物件。這意味著 iterable 可以是另一個 URLSearchParams,在這種情況下,建構函式將簡單地建立所提供的 URLSearchParams 的副本。iterable 的元素是鍵值對,它們本身可以是任何可迭代物件。
允許重複的鍵。
let params;
// Using an array
params = new URLSearchParams([
['user', 'abc'],
['query', 'first'],
['query', 'second'],
]);
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'
// Using a Map object
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// Prints 'user=abc&query=xyz'
// Using a generator function
function* getQueryPairs() {
yield ['user', 'abc'];
yield ['query', 'first'];
yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'
// Each key-value pair must have exactly two elements
new URLSearchParams([
['user', 'abc', 'error'],
]);
// Throws TypeError [ERR_INVALID_TUPLE]:
// Each query pair must be an iterable [name, value] tuple
urlSearchParams.append(name, value)#
將新的鍵值對附加到查詢字串中。
urlSearchParams.delete(name[, value])#
如果提供了 value,則移除所有名稱為 name 且值為 value 的鍵值對。
如果未提供 value,則移除所有名稱為 name 的鍵值對。
urlSearchParams.entries()#
- 回傳:
<Iterator>
返回查詢中每個鍵值對的 ES6 Iterator。迭代器的每個項目都是一個 JavaScript Array。Array 的第一個項目是 name,第二個項目是 value。
urlSearchParams.forEach(fn[, thisArg])#
fn<Function>對查詢中的每個鍵值對呼叫的函數thisArg<Object>呼叫fn時用作this的值
迭代查詢中的每個鍵值對並呼叫給定的函數。
const myURL = new URL('https://example.org/?a=b&c=d');
myURL.searchParams.forEach((value, name, searchParams) => {
console.log(name, value, myURL.searchParams === searchParams);
});
// Prints:
// a b true
// c d true
urlSearchParams.get(name)#
返回名稱為 name 的第一個鍵值對的值。如果沒有這樣的配對,則返回 null。
urlSearchParams.getAll(name)#
name<string>- 傳回:
<string[]>
返回名稱為 name 的所有鍵值對的值。如果沒有這樣的配對,則返回一個空陣列。
urlSearchParams.has(name[, value])#
根據 name 和選用的 value 參數檢查 URLSearchParams 物件是否包含鍵值對。
如果提供了 value,則在存在具有相同 name 和 value 的鍵值對時返回 true。
如果未提供 value,則如果至少有一個名稱為 name 的鍵值對,則返回 true。
urlSearchParams.keys()#
- 回傳:
<Iterator>
返回每個鍵值對名稱的 ES6 Iterator。
const params = new URLSearchParams('foo=bar&foo=baz');
for (const name of params.keys()) {
console.log(name);
}
// Prints:
// foo
// foo
urlSearchParams.set(name, value)#
將 URLSearchParams 物件中與 name 關聯的值設定為 value。如果存在任何名稱為 name 的預先存在的鍵值對,將第一個此類配對的值設定為 value 並移除所有其他配對。如果沒有,則將鍵值對附加到查詢字串中。
const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('foo', 'baz');
params.append('abc', 'def');
console.log(params.toString());
// Prints foo=bar&foo=baz&abc=def
params.set('foo', 'def');
params.set('xyz', 'opq');
console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq
urlSearchParams.size#
參數項目的總數。
urlSearchParams.sort()#
按名稱對所有現有鍵值對進行就地排序。排序使用 穩定排序演算法 完成,因此保留具有相同名稱的鍵值對之間的相對順序。
此方法特別可以用於增加快取命中率。
const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
params.sort();
console.log(params.toString());
// Prints query%5B%5D=abc&query%5B%5D=123&type=search
urlSearchParams.toString()#
- 傳回:
<string>
返回序列化為字串的搜尋參數,並在必要時對字元進行百分比編碼。
urlSearchParams.values()#
- 回傳:
<Iterator>
返回每個鍵值對之值的 ES6 Iterator。
urlSearchParams[Symbol.iterator]()#
- 回傳:
<Iterator>
返回查詢字串中每個鍵值對的 ES6 Iterator。迭代器的每個項目都是一個 JavaScript Array。Array 的第一個項目是 name,第二個項目是 value。
urlSearchParams.entries() 的別名。
const params = new URLSearchParams('foo=bar&xyz=baz');
for (const [name, value] of params) {
console.log(name, value);
}
// Prints:
// foo bar
// xyz baz
url.domainToASCII(domain)#
返回 domain 的 Punycode ASCII 序列化。如果 domain 是無效網域,則返回空字串。
它執行與 url.domainToUnicode() 相反的操作。
import url from 'node:url'; console.log(url.domainToASCII('español.com')); // Prints xn--espaol-zwa.com console.log(url.domainToASCII('中文.com')); // Prints xn--fiq228c.com console.log(url.domainToASCII('xn--iñvalid.com')); // Prints an empty stringconst url = require('node:url'); console.log(url.domainToASCII('español.com')); // Prints xn--espaol-zwa.com console.log(url.domainToASCII('中文.com')); // Prints xn--fiq228c.com console.log(url.domainToASCII('xn--iñvalid.com')); // Prints an empty string
url.domainToUnicode(domain)#
返回 domain 的 Unicode 序列化。如果 domain 是無效網域,則返回空字串。
它執行與 url.domainToASCII() 相反的操作。
import url from 'node:url'; console.log(url.domainToUnicode('xn--espaol-zwa.com')); // Prints español.com console.log(url.domainToUnicode('xn--fiq228c.com')); // Prints 中文.com console.log(url.domainToUnicode('xn--iñvalid.com')); // Prints an empty stringconst url = require('node:url'); console.log(url.domainToUnicode('xn--espaol-zwa.com')); // Prints español.com console.log(url.domainToUnicode('xn--fiq228c.com')); // Prints 中文.com console.log(url.domainToUnicode('xn--iñvalid.com')); // Prints an empty string
url.fileURLToPath(url[, options])#
url<URL>|<string>要轉換為路徑的檔案 URL 字串或 URL 物件。options<Object>windows<boolean>|<undefined>如果path應作為 Windows 檔案路徑返回則為true,POSIX 則為false,系統預設則為undefined。預設值:undefined。
- 返回:
<string>完整解析後的平台特定 Node.js 檔案路徑。
此函數確保百分比編碼字元的正確解碼,並確保跨平台有效的絕對路徑字串。
安全性考量
此函數會解碼百分比編碼的字元,包括編碼的點段(%2e 為 .,%2e%2e 為 ..),然後正規化結果路徑。這意味著編碼的目錄遍歷序列(例如 %2e%2e)會被解碼並作為實際的路徑遍歷處理,即使編碼的斜線(%2F、%5C)被正確拒絕。
應用程式不得僅依賴 fileURLToPath() 來防止目錄遍歷攻擊。 在將返回的路徑值用於檔案系統操作之前,請務必對其進行明確的路徑驗證和安全性檢查,以確保其保持在預期的邊界內。
import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) new URL('file:///hello world').pathname; // Incorrect: /hello%20world fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)const { fileURLToPath } = require('node:url'); new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) new URL('file:///hello world').pathname; // Incorrect: /hello%20world fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
url.fileURLToPathBuffer(url[, options])#
url<URL>|<string>要轉換為路徑的檔案 URL 字串或 URL 物件。options<Object>windows<boolean>|<undefined>如果path應作為 Windows 檔案路徑返回則為true,POSIX 則為false,系統預設則為undefined。預設值:undefined。
- 返回:
<Buffer>作為<Buffer>的完整解析後的平台特定 Node.js 檔案路徑。
除了返回路徑的字串表示形式外,與 url.fileURLToPath(...) 類似,但返回的是 Buffer。當輸入 URL 包含不是有效 UTF-8 / Unicode 序列的百分比編碼片段時,此轉換很有幫助。
安全性考量
此函數具有與 url.fileURLToPath() 相同的安全性考量。它會解碼百分比編碼的字元,包括編碼的點段(%2e 為 .,%2e%2e 為 ..),並正規化路徑。應用程式不得僅依賴此函數來防止目錄遍歷攻擊。 在將返回的緩衝區值用於檔案系統操作之前,請務必對其進行明確的路徑驗證。
url.format(URL[, options])#
URL<URL>一個 WHATWG URL 物件options<Object>- 傳回:
<string>
返回 WHATWG URL 物件之 URL String 表示形式的可自訂序列化結果。
URL 物件具有返回 URL 字串序列化的 toString() 方法和 href 屬性。但是,這些都無法以任何方式自訂。url.format(URL[, options]) 方法允許對輸出進行基本自訂。
import url from 'node:url'; const myURL = new URL('https://a:b@測試?abc#foo'); console.log(myURL.href); // Prints https://a:b@xn--g6w251d/?abc#foo console.log(myURL.toString()); // Prints https://a:b@xn--g6w251d/?abc#foo console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); // Prints 'https://測試/?abc'const url = require('node:url'); const myURL = new URL('https://a:b@測試?abc#foo'); console.log(myURL.href); // Prints https://a:b@xn--g6w251d/?abc#foo console.log(myURL.toString()); // Prints https://a:b@xn--g6w251d/?abc#foo console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); // Prints 'https://測試/?abc'
url.pathToFileURL(path[, options])#
path<string>要轉換為檔案 URL 的路徑。options<Object>windows<boolean>|<undefined>如果path應被視為 Windows 檔案路徑則為true,POSIX 則為false,系統預設則為undefined。預設值:undefined。
- 返回:
<URL>檔案 URL 物件。
此函數確保 path 被解析為絕對路徑,並且在轉換為檔案 URL 時正確編碼 URL 控制字元。
import { pathToFileURL } from 'node:url'; new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)const { pathToFileURL } = require('node:url'); new URL(__filename); // Incorrect: throws (POSIX) new URL(__filename); // Incorrect: C:\... (Windows) pathToFileURL(__filename); // Correct: file:///... (POSIX) pathToFileURL(__filename); // Correct: file:///C:/... (Windows) new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)
url.urlToHttpOptions(url)#
url<URL>要轉換為選項物件的 WHATWG URL 物件。- 返回:
<Object>選項物件protocol<string>要使用的協定。hostname<string>發出請求的伺服器網域名稱或 IP 位址。hash<string>URL 的片段部分。search<string>URL 序列化後的查詢部分。pathname<string>URL 的路徑部分。path<string>請求路徑。應包含查詢字串(如果有)。例如'/index.html?page=12'。當請求路徑包含非法字元時會拋出異常。目前只有空格被拒絕,但未來可能會改變。href<string>序列化後的 URL。port<number>遠端伺服器的連接埠。auth<string>基本身分驗證,即'user:password',用以計算 Authorization 標頭。
此公用程式函數將 URL 物件轉換為 http.request() 和 https.request() API 所預期的普通選項物件。
import { urlToHttpOptions } from 'node:url'; const myURL = new URL('https://a:b@測試?abc#foo'); console.log(urlToHttpOptions(myURL)); /* { protocol: 'https:', hostname: 'xn--g6w251d', hash: '#foo', search: '?abc', pathname: '/', path: '/?abc', href: 'https://a:b@xn--g6w251d/?abc#foo', auth: 'a:b' } */const { urlToHttpOptions } = require('node:url'); const myURL = new URL('https://a:b@測試?abc#foo'); console.log(urlToHttpOptions(myURL)); /* { protocol: 'https:', hostname: 'xn--g6w251d', hash: '#foo', search: '?abc', pathname: '/', path: '/?abc', href: 'https://a:b@xn--g6w251d/?abc#foo', auth: 'a:b' } */
舊版 URL API#
穩定性:3 - 舊版:請改用 WHATWG URL API。
舊版 urlObject#
舊版 urlObject (require('node:url').Url 或 import { Url } from 'node:url') 是由 url.parse() 函數建立並返回的。
urlObject.auth#
auth 屬性是 URL 的使用者名稱和密碼部分,也稱為 userinfo。此字串子集位於 protocol 和雙斜線(如果存在)之後,並在 host 組件之前,由 @ 分隔。該字串可以是使用者名稱,也可以是使用者名稱和以 : 分隔的密碼。
例如:'user:pass'。
urlObject.hash#
hash 屬性是 URL 的片段標識符部分,包含開頭的 # 字元。
例如:'#hash'。
urlObject.host#
host 屬性是 URL 的完整小寫主機部分,如果指定了 port,則包含在內。
例如:'sub.example.com:8080'。
urlObject.hostname#
hostname 屬性是 host 組件的小寫主機名稱部分,不 包含 port。
例如:'sub.example.com'。
urlObject.href#
href 屬性是解析後的完整 URL 字串,其中 protocol 和 host 組件都已轉換為小寫。
例如:'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'。
urlObject.path#
path 屬性是 pathname 和 search 組件的串接。
例如:'/p/a/t/h?query=string'。
不會對 path 執行解碼。
urlObject.pathname#
pathname 屬性由 URL 的整個路徑部分組成。這是 host(包括 port)之後、query 或 hash 組件開始之前的所有內容,由 ASCII 問號 (?) 或井字號 (#) 字元分隔。
例如:'/p/a/t/h'。
不會對路徑字串執行解碼。
urlObject.port#
port 屬性是 host 組件的數字連接埠部分。
例如:'8080'。
urlObject.protocol#
protocol 屬性識別 URL 的小寫協定方案。
例如:'http:'。
urlObject.query#
query 屬性是不含開頭 ASCII 問號 (?) 的查詢字串,或者是 querystring 模組之 parse() 方法返回的物件。query 屬性是字串還是物件,取決於傳遞給 url.parse() 的 parseQueryString 參數。
例如:'query=string' 或 {'query': 'string'}。
如果以字串形式返回,則不會對查詢字串執行解碼。如果以物件形式返回,則鍵和值都會被解碼。
urlObject.search#
search 屬性由 URL 的整個「查詢字串」部分組成,包含開頭的 ASCII 問號 (?) 字元。
例如:'?query=string'。
不會對查詢字串執行解碼。
urlObject.slashes#
slashes 屬性是一個 boolean,如果 protocol 中的冒號後面需要兩個 ASCII 正斜線字元 (/),則其值為 true。
url.format(urlObject)#
urlObject<Object>一個 URL 物件(如url.parse()返回或以其他方式建構的)。
url.format() 方法返回從 urlObject 派生的格式化 URL 字串。
const url = require('node:url');
url.format({
protocol: 'https',
hostname: 'example.com',
pathname: '/some/path',
query: {
page: 1,
format: 'json',
},
});
// => 'https://example.com/some/path?page=1&format=json'
如果 urlObject 不是物件或字串,url.format() 將拋出 TypeError。
格式化程序的操作如下:
- 建立一個新的空字串
result。 - 如果
urlObject.protocol是字串,則將其原樣附加到result。 - 否則,如果
urlObject.protocol不是undefined且不是字串,則拋出Error。 - 對於
urlObject.protocol之中 不以 ASCII 冒號 (:) 字元結尾的所有字串值,字面字串:將被附加到result。 - 如果滿足以下任一條件,則字面字串
//將被附加到result:urlObject.slashes屬性為 true;urlObject.protocol以http、https、ftp、gopher或file開頭;
- 如果
urlObject.auth屬性的值為真,且urlObject.host或urlObject.hostname不是undefined,則urlObject.auth的值將被強制轉換為字串並附加到result,後跟字面字串@。 - 如果
urlObject.host屬性為undefined,則:- 如果
urlObject.hostname是字串,則將其附加到result。 - 否則,如果
urlObject.hostname不是undefined且不是字串,則拋出Error。 - 如果
urlObject.port屬性值為真,且urlObject.hostname不是undefined:- 字面字串
:被附加到result,且 urlObject.port的值被強制轉換為字串並附加到result。
- 字面字串
- 如果
- 否則,如果
urlObject.host屬性值為真,則urlObject.host的值被強制轉換為字串並附加到result。 - 如果
urlObject.pathname屬性是一個非空字串:- 如果
urlObject.pathname不以 ASCII 正斜線 (/) 開頭,則將字面字串'/'附加到result。 - 將
urlObject.pathname的值附加到result。
- 如果
- 否則,如果
urlObject.pathname不是undefined且不是字串,則拋出Error。 - 如果
urlObject.search屬性為undefined,且如果urlObject.query屬性是一個Object,則將字面字串?附加到result,後跟呼叫querystring模組之stringify()方法並傳遞urlObject.query值的輸出。 - 否則,如果
urlObject.search是字串:- 如果
urlObject.search的值 不以 ASCII 問號 (?) 字元開頭,則將字面字串?附加到result。 - 將
urlObject.search的值附加到result。
- 如果
- 否則,如果
urlObject.search不是undefined且不是字串,則拋出Error。 - 如果
urlObject.hash屬性是字串:- 如果
urlObject.hash的值 不以 ASCII 井字號 (#) 字元開頭,則將字面字串#附加到result。 - 將
urlObject.hash的值附加到result。
- 如果
- 否則,如果
urlObject.hash屬性不是undefined且不是字串,則拋出Error。 - 返回
result。
提供自動化遷移方案 (原始碼)。
npx codemod@latest @nodejs/node-url-to-whatwg-url
url.format(urlString)#
穩定性:0 - 已棄用:請改用 WHATWG URL API。
urlString<string>將傳遞給url.parse()然後進行格式化的字串。
url.format(urlString) 是 url.format(url.parse(urlString)) 的簡寫。
因為它在內部呼叫了已棄用的 url.parse(),所以將字串參數傳遞給 url.format() 本身也是已棄用的。
URL 字串的規範化可以使用 WHATWG URL API 執行,方法是建構一個新的 URL 物件並呼叫 url.toString()。
import { URL } from 'node:url'; const unformatted = 'http://[fe80:0:0:0:0:0:0:1]:/a/b?a=b#abc'; const formatted = new URL(unformatted).toString(); console.log(formatted); // Prints: http://[fe80::1]/a/b?a=b#abcconst { URL } = require('node:url'); const unformatted = 'http://[fe80:0:0:0:0:0:0:1]:/a/b?a=b#abc'; const formatted = new URL(unformatted).toString(); console.log(formatted); // Prints: http://[fe80::1]/a/b?a=b#abc
url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#
穩定性:0 - 已棄用:請改用 WHATWG URL API。
urlString<string>要解析的 URL 字串。parseQueryString<boolean>如果為true,則query屬性將始終設定為querystring模組之parse()方法返回的物件。如果為false,則返回的 URL 物件上的query屬性將是未解析、未解碼的字串。預設值:false。slashesDenoteHost<boolean>如果為true,則字面字串//之後且在下一個/之前的第一個標記將被解釋為host。例如,給定//foo/bar,結果將是{host: 'foo', pathname: '/bar'}而不是{pathname: '//foo/bar'}。預設值:false。
url.parse() 方法接收一個 URL 字串,對其進行解析,並返回一個 URL 物件。
如果 urlString 不是字串,則拋出 TypeError。
如果 auth 屬性存在但無法解碼,則拋出 URIError。
url.parse() 使用寬鬆、非標準的演算法來解析 URL 字串。它容易出現安全性問題,例如 主機名稱偽造 (hostname spoofing) 以及對使用者名稱和密碼處理不當。請勿將其用於不可信的輸入。不會針對 url.parse() 的弱點發布 CVE。請改用 WHATWG URL API,例如:
function getURL(req) {
const proto = req.headers['x-forwarded-proto'] || 'https';
const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com';
return new URL(`${proto}://${host}${req.url || '/'}`);
}
上述範例假設格式良好的標頭從反向代理轉發到您的 Node.js 伺服器。如果您沒有使用反向代理,則應使用以下範例:
function getURL(req) {
return new URL(`https://example.com${req.url || '/'}`);
}
提供自動化遷移方案 (原始碼)。
npx codemod@latest @nodejs/node-url-to-whatwg-url
url.resolve(from, to)#
穩定性:0 - 已棄用:請改用 WHATWG URL API。
url.resolve() 方法以類似於網頁瀏覽器解析錨點標籤 (anchor tag) 的方式,相對於基準 URL 解析目標 URL。
const url = require('node:url');
url.resolve('/one/two/three', 'four'); // '/one/two/four'
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
因為它在內部呼叫了已棄用的 url.parse(),所以 url.resolve() 本身也已棄用。
使用 WHATWG URL API 達成相同結果:
function resolve(from, to) {
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
if (resolvedUrl.protocol === 'resolve:') {
// `from` is a relative URL.
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
}
resolve('/one/two/three', 'four'); // '/one/two/four'
resolve('http://example.com/', '/one'); // 'http://example.com/one'
resolve('http://example.com/one', '/two'); // 'http://example.com/two'
URL 中的百分比編碼#
URL 僅允許包含特定範圍的字元。任何落在該範圍之外的字元都必須進行編碼。此類字元如何編碼,以及要編碼哪些字元,完全取決於該字元在 URL 結構中所處的位置。
舊版 API#
在舊版 API 中,空格 (' ') 和以下字元將在 URL 物件的屬性中自動逸出:
< > " ` \r \n \t { } | \ ^ '
例如,ASCII 空格字元 (' ') 被編碼為 %20。ASCII 正斜線 (/) 字元被編碼為 %3C。
WHATWG API#
WHATWG URL 標準 與舊版 API 相比,在選擇編碼字元方面使用更具選擇性且更細緻的方法。
WHATWG 演算法定義了四個「百分比編碼集合」,描述了必須進行百分比編碼的字元範圍:
-
C0 控制百分比編碼集 (C0 control percent-encode set) 包括 U+0000 到 U+001F(含)範圍內的碼位,以及所有大於 U+007E (~) 的碼位。
-
片段百分比編碼集 (fragment percent-encode set) 包括 C0 控制百分比編碼集 以及碼位 U+0020 SPACE、U+0022 (")、U+003C (<)、U+003E (>) 和 U+0060 (`)。
-
路徑百分比編碼集 (path percent-encode set) 包括 C0 控制百分比編碼集 以及碼位 U+0020 SPACE、U+0022 (")、U+0023 (#)、U+003C (<)、U+003E (>)、U+003F (?)、U+0060 (`)、U+007B ({) 和 U+007D (})。
-
使用者資訊編碼集 (userinfo encode set) 包括 路徑百分比編碼集 以及碼位 U+002F (/)、U+003A (:)、U+003B (;)、U+003D (=)、U+0040 (@)、U+005B ([) 到 U+005E(^),以及 U+007C (|)。
使用者資訊百分比編碼集 專門用於 URL 內編碼的使用者名稱和密碼。路徑百分比編碼集 用於大多數 URL 的路徑。片段百分比編碼集 用於 URL 片段。除了所有其他情況外,C0 控制百分比編碼集 在某些特定條件下用於主機和路徑。
當主機名稱中出現非 ASCII 字元時,主機名稱將使用 Punycode 演算法進行編碼。但請注意,主機名稱 可能 同時包含 Punycode 編碼和百分比編碼的字元:
const myURL = new URL('https://%CF%80.example.com/foo');
console.log(myURL.href);
// Prints https://xn--1xa.example.com/foo
console.log(myURL.origin);
// Prints https://xn--1xa.example.com