如何判断 SvelteKit 的“加载”功能是在服务器还是客户端上运行?

cam*_*aca 4 svelte sveltekit

我正在尝试通过加载函数在 SvelteKit 页面中进行 API 调用,但我不想用本地端点代理这些调用,因为我想让 Web 服务器尽可能轻巧。

我特别想做的是,当从服务器调用时,API 的 URL 应该与从客户端调用时不同(例如“http://localhost:1234”与“https://example.js”)。 com:1234",分别)。

但是,比这更普遍的是,有没有办法区分当前代码是在服务器上还是在客户端上运行?

pha*_*eth 8

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>
Run Code Online (Sandbox Code Playgroud)

以下来自SvelteKit 的文档

browser 是 true 还是 false 取决于应用程序是在浏览器中还是在服务器上运行


Jac*_*ace 6

免责声明:我写的不是标题的真正答案,而是所描述问题的具体答案。

有一个目标钩子函数handleFetch),它的构建是为了在客户端或服务器上以不同的方式寻址资源:

https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch

/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
    if (request.url.startsWith('https://api.yourapp.com/')) {
        // clone the original request, but change the URL
        request = new Request(
            request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),
            request
        );
    }

    return fetch(request);
}
Run Code Online (Sandbox Code Playgroud)