Search code examples
sveltesveltekit

SvelteKit Load data from backend to component


I have a Java Spring API i want to get data from , and display them in my component eg. Test.svelte i use in my +layout.svelte . I dont want to have a fetch directly to the Api But the svelte application first .

User (Test.svelte) <-> SvelteApplication <-> API

What is the correct way to do this ?

I Have tried using the accepted approach here

Create a svelte component with a function recive a data by post

By creating a Test.js but it dosent seem to ever fetch data (Tried logging in console) and my variables stay as undefined .


Solution

  • The API has since changed, see the docs on routing.

    API methods are associated with the current route (directory-based) via a +server.js/ts file. E.g. if you have a +page.svelte and a +server.js/ts directly in src/routes, they both refer to the / route (unless a different base URL is set). For layouts you get a layout.server.js/ts file instead, they do not support anything other than the load function, though, as they are not bound to a specific route.

    Using those two files you could send a request like this:

    <!-- +page.svelte -->
    <script>
        async function onRequest() {
            const res = await fetch('/', { method: 'POST' });
    
            if (res.ok == false) {
                alert('Error');
                return;
            }
            
            const result = await res.json();
            alert('OK: ' + result.value);
        }
    </script>
    
    <button on:click={onRequest}>Request</button>
    
    // +server.js
    import { json } from '@sveltejs/kit';
    
    export const POST = () => json({ value: 42 });