Last active
October 12, 2022 19:17
-
-
Save philsinatra/b614fb8df38a9b1aefc8f732883af38a to your computer and use it in GitHub Desktop.
Svelte POST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="ts"> | |
import { onMount } from 'svelte'; | |
let title: string; | |
onMount(() => { | |
try { | |
fetch('/api/post', { | |
method: 'post', | |
headers: { 'Content-Type': 'application/json' }, | |
body: JSON.stringify({ title: 'Svelte API POST' }) | |
}) | |
.then((response) => response.json()) | |
.then((data) => { | |
title = data.body.title; | |
}) | |
.catch((error) => { | |
console.error('error', error); | |
}); | |
} catch (error) { | |
console.error('error', error); | |
} | |
}); | |
</script> | |
{#if title} | |
<p>{title}</p> | |
{/if} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function POST({ request }: { request: Request }) { | |
// https://bit.ly/3yEls4L | |
const body = await request.json(); | |
try { | |
return new Response(JSON.stringify({ body }), { | |
status: 200 | |
}); | |
} catch (error) { | |
console.error('error', error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment