在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
确定是否需要使用fetch
或node-fetch
。
是否有更好的方法来克服Sapper的限制?
您提出的解决方案是最常见的解决方案。另一种选择是将this.fetch
作为参数与其他参数一起传递给getJson方法:
<script context="module">
import {getJson} from 'api';
export async function preload() {
const res = await getJson(this.fetch);
}
</script>