首页 > 解决方案 > 如何在路线之外的 Sapper 项目中使用 fetch?

问题描述

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

一个解决方案可能是在 api 服务中为 Node 使用 HTTP 客户端node-fetch,然后在运行时确定process.browser我们是否需要使用fetchor node-fetch

有没有更好的方法来克服这个 Sapper 限制?

标签: sveltesapper

解决方案


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

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

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

推荐阅读