Search code examples
jsonfetchlocalsveltesapper

Sapper/Svelte: how to fetch a local json file to retrieve data


In my sapper app, I have some data stored in a json file at src/data/videoslist.json, an array of objects in json format.

I need to retrive the data in my index page to pass it to the component. Here's my code at the top of src/routes/index.svelte

<script context="module">
    export async function preload() {
        const response = await this.fetch('../data/videoslist.json');
        const responseJson = await response.json();
        return {
            videos: responseJson
        }
    }
</script>

I get an error 500

invalid json response body at http://127.0.0.1:3000/data/videoslist.json reason: Unexpected token < in JSON at position 0

The file is pure json, nothing else. The unexpected token < makes me think a 404 is returned instead of the file.

Do you know what I get wrong ? I tried so many paths variations wit ../ ./ or moving the file to the route folder, but nothing works.

PS: I'm still a newbie with js and framework stuff, I may have missed something very basic for someone who knows better :) (like you can't retrieve a local file with fetch).


Solution

  • Write the JSON file into the static folder, as static/data/videoslist.json.