如何在路线之外的Sapper项目中使用提取?

问题描述 投票:0回答:1

在Sapper中,可以在this.fetch内部的preload()功能中使用<script context="module">。然后,Sapper确定是使用客户端版本还是服务器版本fetch

<script context="module">
    export async function preload() {
        const res = await this.fetch(`something.json`);
    }
</script>

将您的所有请求写在路由中无法很好地扩展,因此有必要创建api服务来执行以下操作:

<script context="module">
    import {getJson} from 'api';

    export async function preload() {
        const res = await getJson();
    }
</script>

这会产生问题,因为在preload()函数外部没有Sapper提供的this上下文,因此在Node上下文中运行时(加载应用程序的第一页并执行SSR时)没有this.fetch可用。之后,所有请求都从浏览器发出,因此常规的fetch可用。

一种解决方案是在api服务中对HTTP客户端使用类似于node-fetch的节点,然后在运行时使用process.browser确定是否需要使用fetchnode-fetch

是否有更好的方法来克服Sapper的限制?

svelte sapper
1个回答
0
投票

您提出的解决方案是最常见的解决方案。另一种选择是将this.fetch作为参数与其他参数一起传递给getJson方法:

<script context="module">
    import {getJson} from 'api';

    export async function preload() {
        const res = await getJson(this.fetch);
    }
</script>
© www.soinside.com 2019 - 2024. All rights reserved.