svelte - sapper 作为静态站点生成器
问题描述
我想用工兵作为ssg。当我得到这样的数据时:
<script context="module">
export function preload({ params, query }) {
return this.fetch(`https://jsonplaceholder.typicode.com/posts`)
.then(r => r.json())
.then(posts => {
return {posts}
})
}
我可以将网站导出为静态。但是在链接上,数据仍然从 jsonplaceholder 中获取。只有在重新加载时,数据才会从静态文件夹中获取。如何获取所有获取的静态数据?
解决方案
因此,这在开始时可能会有些混乱。要使其正常工作,您需要在本地代理您的提取。您可以这样做:
在/posts/index.json.js
:
let contents;
export function get(req, res) {
const posts = fetch('do stuff here to fetch')
contents = JSON.stringify(posts);
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(contents);
}
在您的实际路线组件中/posts/index.svelte
:
<script context="module">
export async function preload({ params, query }) {
return this.fetch(`index.json`).then(r => r.json()).then(posts => {
return { posts };
});
}
</script>
<script>
export let posts;
</script>
Svelte官方网站使用这种方法来获取帖子(从本地文件而不是使用 fetch)。你可能会从中得到一些启发。
值得一提的是,该preload()
函数同时发送到服务器和前端,因此您不应将 API 密钥放在那里。
推荐阅读
- fortran - 使用 MPI_Allgather 收集不同大小的数组
- php - laravel 为用户设置个人资料页面错误属性 [user] 在此集合实例上不存在
- php - 我可以使用 API 在移动设备中使用服务器端支付集成吗
- php - 数据表未显示来自查询的所有数据
- javascript - 切换表格的显示:不是第一列
- java - 如何在数组中打印 [ ] (Java)
- visual-studio - 使用 Visual Studio 2017 Docker build 未将 site.css 样式应用于 Docker 映像
- c# - 将 C# 流式接口转换为 VB.NET 中的代码
- amazon-web-services - 使用 AWS cognito 将自己的 api 作为第三方
- javascript - 将 data-dismiss="modal" 绑定到键单击