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

时间:2020-04-14 04:04:16

标签: svelte sapper

在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上下文中运行时(加载第一页时)没有this.fetch可用应用程序并执行SSR)。之后,所有请求都从浏览器发出,因此常规fetch可用。

一种解决方案可能是在api服务中为像node-fetch之类的节点使用HTTP客户端,然后在运行时使用process.browser确定是否需要使用fetch或{{1} }。

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

2 个答案:

答案 0 :(得分:2)

您想到的解决方案是最常见的解决方案。 一种替代方法是将this.fetch作为参数与其他参数一起传递给getJson方法:

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

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

答案 1 :(得分:0)

this.fetch仅用于路由(在Nuxt中考虑asyncData)。 使用Axios也是一种常见的解决方案,因为它允许编写可以在两种环境中执行相同代码而无需修补fetch的代码(就像使用node-fetch一样)。