svelte - 如何判断 SvelteKit 的 "load"函数是在服务器还是客户端上运行?

标签 svelte sveltekit

我正在尝试在来自 load 的 SvelteKit 页面中进行 API 调用函数,但我不想用本地端点代理这些调用,因为我想让 Web 服务器尽可能轻。
我特别想做的是,当从服务器调用时,API 的 URL 应该与从客户端调用时不同(例如“http://localhost:1234”与“https://example.js”)。 com:1234",分别)。
但是,更普遍的是,有没有办法区分当前代码是在服务器上还是在客户端上运行?

最佳答案

load函数有使用 browser 的选项从 $app/env 导入后的标志.

<script context="module">
    import { browser } from '$app/env'; 
    ...
    export async function load({ fetch }) {
        if (!browser) {
            // code here runs only on the server
        }
        return {
           ...
        }
    }
    ...
<script>
以下来自SvelteKit's docs :

browser is true or false depending on whether the app is running in the browser or on the server

关于svelte - 如何判断 SvelteKit 的 "load"函数是在服务器还是客户端上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67808939/

相关文章:

javascript - 错误 : {#each} only iterates over array-like objects. - Javascript 和 Svelte

svelte - 如何将 Google Adsense 添加到 Svelte/Sapper 网络应用程序?

google-analytics - SvelteKit 谷歌分析双重报告

javascript - Sveltekit 加载函数显然没有被调用

import - 由 "ENV_VAR_NAME"导入的 RollupError : "$env/static/private" is not exported by "src/hooks.server.js", 。 - SvelteKit

javascript - 将 SVG 图标导入 Svelte 应用程序的最佳方式

svelte - 无法使用 Sapper 导出生成动态路由

svelte - 如何检索 Sveltekit page.js 文件上的 localStorage 数据?

ethereum - slim 和 web3- ReferenceError : process is not defined

javascript - 我可以在 Svelte 中使用 React 组件吗?