首页 > 解决方案 > 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 中获取。只有在重新加载时,数据才会从静态文件夹中获取。如何获取所有获取的静态数据?

标签: sveltesapper

解决方案


因此,这在开始时可能会有些混乱。要使其正常工作,您需要在本地代理您的提取。您可以这样做:

/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 密钥放在那里。


推荐阅读