在工兵它可以使用this.fetch在preload()函数内部<script context="module">。然后 Sapper 确定是使用客户端还是服务器版本的fetch.
<script context="module">
export async function preload() {
const res = await this.fetch(`something.json`);
}
</script>
Run Code Online (Sandbox Code Playgroud)
在路由中写入所有请求并不能很好地扩展,因此必须创建一个api服务来执行以下操作:
<script context="module">
import {getJson} from 'api';
export async function preload() {
const res = await getJson();
}
</script>
Run Code Online (Sandbox Code Playgroud)
这会产生一个问题,因为在preload()函数之外没有thisSapper 提供的上下文,因此this.fetch在 Node 上下文中运行时(加载应用程序的第一页并执行 SSR 时)不可用。之后所有请求都从浏览器发出,因此常规fetch可用。
一个解决方案可能是像node-fetch在 api 服务中一样为 Node 使用 HTTP 客户端,然后在运行时确定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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1197 次 |
| 最近记录: |