0

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 .

1
  • 1
    I would not recommend this. Currently it looks like you would need a separate file in a separate folder for every API endpoint with a different path. You could of course define fewer endpoints and work primarily with query parameters or use something like the hooks. Commented Nov 16, 2022 at 16:49

1 Answer 1

2

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 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.