问题
I would like to use sapper as ssg. When I get data like so:
<script context="module">
export function preload({ params, query }) {
return this.fetch(`https://jsonplaceholder.typicode.com/posts`)
.then(r => r.json())
.then(posts => {
return {posts}
})
}
I can export the site to static. But on links the data still gets fetched from jsonplaceholder. Only on reload the data gets from the static folder. How to get all fetched data static?
回答1:
So this can be a bit confusing in the beginning. To get this working you need to proxy your fetches locally. Here's how you can do that:
In /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);
}
And in your actual route component /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>
The official Svelte website uses this approach to get posts (from a local file rather than using fetch though). You can probably get some inspiration from that.
It is worth mentioning that the preload()
function is shipped both to the server and the front-end so you should not put API keys there.
回答2:
This now seems to work. Will test it now. Comments are welcome as I do not feel comfortable and this just was try and error.
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/sapper-as-static-site-generator