Skip to content

Instantly share code, notes, and snippets.

@philsinatra
Last active October 12, 2022 19:17
Show Gist options
  • Save philsinatra/b614fb8df38a9b1aefc8f732883af38a to your computer and use it in GitHub Desktop.
Save philsinatra/b614fb8df38a9b1aefc8f732883af38a to your computer and use it in GitHub Desktop.
Svelte POST API
<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}
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