【问题标题】:sapper as static site generatorsapper 作为静态站点生成器
【发布时间】:2020-07-08 14:53:03
【问题描述】:

我想将 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 中获取。只有在重新加载时,数据才会从静态文件夹中获取。如何将所有获取的数据静态化?

【问题讨论】:

    标签: svelte sapper


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。但是当我尝试时,我得到 FetchError: invalid json response body at 127.0.0.1:3000/index.json reason: Unexpected token blog/index.json)... 但得到 {message: "Not found"}发帖。
    • 尝试自行检查http://127.0.0.1/posts/index.json 的结果。 (即卷曲)
    • 好吧,localhost:3000/posts/index.json 只是给出了一个 404 页面。不应该是localhost:3000/posts.json。在提到的博客模板中,blog/index.json.js 被导出到 /blog.json。我们确实需要导入 node-fetch 吗?
    【解决方案2】:

    这现在似乎有效。现在将对其进行测试。欢迎发表评论,因为我觉得不舒服,这只是尝试和错误。

    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>
    

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2015-07-22
      • 1970-01-01
      • 2013-10-08
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2016-06-02
      相关资源
      最近更新 更多