svelte - 如何在路线之外的 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()
函数之外没有this
Sapper 提供的上下文,因此this.fetch
在 Node 上下文中运行时(加载应用程序的第一页并执行 SSR 时)不可用。之后,所有请求都是从浏览器发出的,因此常规fetch
可用。
一个解决方案可能是在 api 服务中为 Node 使用 HTTP 客户端node-fetch
,然后在运行时确定process.browser
我们是否需要使用fetch
or node-fetch
。
有没有更好的方法来克服这个 Sapper 限制?
解决方案
您提出的解决方案是最常见的解决方案。另一种方法是将this.fetch
其他参数作为参数传递给 getJson 方法:
<script context="module">
import {getJson} from 'api';
export async function preload() {
const res = await getJson(this.fetch);
}
</script>
推荐阅读
- mysql - 创建带有提交和回滚的过程
- javascript - “未经检查的 runtime.lastError:消息端口在收到响应之前关闭。” Chrome 扩展程序
- java - guice 单个常量的多个绑定
- swift - 在三角形 CAShapeLayer 上方添加文本
- javascript - 使用异步导致:错误 [ERR_REQUIRE_ESM]: Must use import to load ES Module asyncToGenerator.js
- python - 单击提交付款按钮后,Django Stripe 付款响应无效参数
- mysql - 外键可以引用多个表吗?
- javascript - 在填写表格之前隐藏文章的其余部分
- php - php说每天都有不同的时区秒数
- go - 使用无服务框架在 API 模式下本地调试 lambda golang