сапер как генератор статических сайтов

Я хотел бы использовать 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} 
        })
}

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?


person user1308302    schedule 27.03.2020    source источник


Ответы (2)


Так что вначале это может немного сбивать с толку. Чтобы это заработало, вам нужно локально проксировать ваши выборки. Вот как это сделать:

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);
}

И в вашем фактическом компоненте маршрута /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 использует этот подход для получения сообщений. (из локального файла, а не с помощью выборки). Вы, вероятно, сможете получить от этого какое-то вдохновение.

Стоит отметить, что функция preload() отправляется как на сервер, так и в интерфейсную часть, поэтому вам не следует помещать туда ключи API.

person kevinak    schedule 28.03.2020
comment
спасибо. Но когда я пытаюсь, я получаю FetchError: недопустимое тело ответа json в 127.0.0.1:3000/index.json причина: Неожиданный токен ‹в JSON в позиции 0 Затем изменился return this.fetch (_1 _) ... но получить {message: Not found} для сообщений. - person user1308302; 28.03.2020
comment
Попробуйте самостоятельно проверить результат http://127.0.0.1/posts/index.json. (т.е. с завитком) - person joshnuss; 28.03.2020
comment
Итак, localhost: 3000 / posts / index.json просто дает страницу 404. Если это не localhost: 3000 / posts.json. В упомянутом шаблоне блога blog / index.json.js экспортируется в /blog.json. А нам нужно импортировать node-fetch? - person user1308302; 29.03.2020

Кажется, теперь это работает. Сейчас протестирую. Комментарии приветствуются, так как я не чувствую себя комфортно, и это просто попытка и ошибка.

сообщения / 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);
}

сообщения / 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>
person user1308302    schedule 29.03.2020