在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的局限性?
答案 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
一样)。