我想使用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获取的。只有在重新加载时,才会从静态文件夹中获取数据。如何让所有获取的数据都是静态的?
发布于 2020-03-28 17:58:58
因此,这在一开始可能会有点混乱。为了让它正常工作,你需要在本地代理你的抓取。下面是你如何做到这一点:
在/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 website使用这种方法来获取帖子(虽然是从本地文件而不是使用fetch )。你可能会从中得到一些启发。
值得一提的是,preload()函数同时提供给服务器和前端,因此您不应该将API键放在那里。
发布于 2020-03-30 01:33:17
现在,这似乎起作用了。现在就来测试一下。欢迎评论,因为我感到不舒服,这只是尝试和错误。
posts/index.json.js
import fetch from 'node-fetch'
export async function get(req, res) {
const posts = await fetch('https://jsonplaceholder.typicode.com/posts')
const contents = await posts.text()
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(`posts.json`).then(r => r.json()).then(posts => {
return { posts };
});
}
</script>https://stackoverflow.com/questions/60893250
复制相似问题