跳至主要内容

位置 API

Deno 支持来自 web 的 location 全局变量。请继续阅读。

位置标志

没有“网页”的 URL 可以用于 Deno 进程中的位置。我们允许用户通过使用 --location 标志在 CLI 上指定一个来模拟文档位置。它可以是 httphttps 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".

扩展使用

在 web 上,资源解析(不包括模块)通常使用 location.href 的值作为根,在此基础上构建任何相对 URL。这会影响 Deno 采用的某些 web 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() 调用将抛出异常,因为没有与 Web 相似的地址来作为其基础。

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 全局变量而导致的错误。