How to call local endpoint from button click with SvelteKit

Viewed 591

I can't get my svelte page named card.svelte to call the post method in the card.js.

  <script>
  export let habit
  import { Client } from "@notionhq/client";
  
  //change color of card when clicked
  async function updatePage() {
    habit.green = !habit.green;
    let res = await fetch('formdata', {
      method: 'post',
      headers: {        
        'content-type': 'application/json'
        },
      body: 'test'
    });
    const json = await res.json();
    result = JSON.stringify(json);
    
    console.log(result);
    console.log('update habit');
    return {
      status: result.code,
      body: results
    }
  }
</script>
<form on:submit|preventDefault={updatePage}>
<div class='card' class:selected={habit.green}>
  <div class='habit-title'>{habit.name}</div>
  <button type="submit">Test</button>
</div>
</form>

I get the following error on the chrome console

Fetch failed loading: POST "http://localhost:3000/formdata".

Here's my card.js file.

    import { Client } from "@notionhq/client";

/** @type {import('@sveltejs/kit').RequestHandler} */
export function post(request, params, url) {
  // log all headers
  console.log("ITS WORKING");

  return {
    body: {
      // retrieve a specific header
      test: "test",
    },
  };
}

No errors on terminal.

What am I doing wrong?

My end goal is to call an external API (Notion API) from server-side. But, I can figure the rest out if I can just figure out how to make a button on the svelte page call the local backend api.

Is there an easier way to do this?

forgive me for my ignorance!

1 Answers

You need to fetch your data with onMount function

<script> 
import onMonunt from 'svelte';
import { Client } from '@notionhq/client';

onMount(async () => {
       let res = await fetch('formdata', {
      method: 'post',
      headers: {        
        'content-type': 'application/json'
        },
      body: 'test'
    })'

</script>
Related