位置 API
Deno 支援來自 Web 的location
全域。請繼續閱讀。
位置標記
在 Deno 程序中,沒有「網頁」的 URL 可用於位置。我們允許使用者使用 --location
旗標在 CLI 上指定一個,以模擬文件位置。它可以是 http
或 https
URL。
// deno run --location https://example.com/path main.ts
console.log(location.href);
// "https://example.com/path"
您必須傳遞 --location <href>
才能執行此操作。如果您沒有傳遞,任何對 location
全域變數的存取都會擲回錯誤。
// deno run main.ts
console.log(location.href);
// error: Uncaught ReferenceError: Access to "location", run again with --location <href>.
設定 location
或其任何欄位通常會導致瀏覽器導航。這不適用於 Deno,因此會在這種情況下擲回錯誤。
// deno run --location https://example.com/path main.ts
location.pathname = "./foo";
// error: Uncaught NotSupportedError: Cannot set "location.pathname".
延伸用法
在網路上,資源解析(排除模組)通常使用 location.href
的值作為基礎,以建立任何相對 URL。這會影響 Deno 採用的部分網路 API。
Fetch API
// deno run --location https://api.github.com/ --allow-net main.ts
const response = await fetch("./orgs/denoland");
// Fetches "https://api.github.com/orgs/denoland".
如果未傳遞 --location
旗標,上述 fetch()
呼叫會擲回錯誤,因為沒有類比網路的位置作為基礎。
Worker 模組
// deno run --location https://example.com/index.html --allow-net main.ts
const worker = new Worker("./workers/hello.ts", { type: "module" });
// Fetches worker module at "https://example.com/workers/hello.ts".
僅在必要時使用
對於上述使用案例,最好完整傳遞 URL,而不是依賴 --location
。必要時,您可以使用 URL
建構函數手動建立相對 URL。
--location
旗標是針對那些有特定目的模擬文件位置,並知道這只會在應用程式層級運作的人員。但是,您也可以使用它來消除依賴項中輕率存取 location
全域變數的錯誤。