如何使用SvelteKit从按钮点击调用本地端点



我不能让我的苗条页面命名为card.svelte调用card.js中的post方法。

<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>

我在chrome控制台得到以下错误

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

这是我的card.js文件。

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",
},
};
}

终端没有错误

我做错了什么?

我的最终目标是从服务器端调用外部API (Notion API)。但是,如果我能弄清楚如何使苗条页面上的按钮调用本地后端api,我就能弄清楚其余的。

有更简单的方法吗?

请原谅我的无知!

您需要使用onMount函数获取数据

<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>

最新更新