Skip to main content

데이터를 변경하기 위한 POST 와 같은 요청들도 처리할 수 있습니다. 대부분의 경우엔 폼 액션를 대신 사용하는 것이 더 편합니다. 코드도 더 짧고, 자바스크립트 없이도 작동하며, 더 유연하기(resilient) 때문입니다.

'add a todo' <input> 안의 keydown 이벤트 핸들러에서, 서버로 데이터를 POST 해 봅시다.

src/routes/+page.svelte
<input
	type="text"
	autocomplete="off"
	on:keydown={async (e) => {
		if (e.key !== 'Enter') return;

		const input = e.currentTarget;
		const description = input.value;

		const response = await fetch('/todo', {
			method: 'POST',
			body: JSON.stringify({ description }),
			headers: {
				'Content-Type': 'application/json'
			}
		});

		input.value = '';
	}}
/>

이제 JSON을 /todo API 라우트로 포스트 해봅시다. 쿠키에 있는 userid 값을 보내고, 응답 안에 있는 새 할 일의 id 를 받아봅시다.

src/routes/todo/+server.js 파일에 src/lib/server/database.js에 있는 createTodo를 호출하는 POST 핸들러를 만들어 봅시다.

src/routes/todo/+server.js
import { json } from '@sveltejs/kit';
import * as database from '$lib/server/database.js';

export async function POST({ request, cookies }) {
	const { description } = await request.json();

	const userid = cookies.get('userid');
	const { id } = await database.createTodo({ userid, description });

	return json({ id }, { status: 201 });
}

load 함수와 폼 액션과 마찬가지로, request는 표준 리퀘스트(Request) 객체입니다. 그러므로 await request.json()는 이벤트 핸들러로 포스트 된 데이터를 반환합니다.

데이터베이스에 새롭게 생긴 할 일의 id201 Created 상태 코드로 반환하고 있습니다. 이벤트 핸들러에서 이 값을 이용해 페이지를 업데이트 해도록 바꿔 봅시다.

src/routes/+page.svelte
<input
	type="text"
	autocomplete="off"
	on:keydown={async (e) => {
		if (e.key !== 'Enter') return;

		const input = e.currentTarget;
		const description = input.value;

		const response = await fetch('/todo', {
			method: 'POST',
			body: JSON.stringify({ description }),
			headers: {
				'Content-Type': 'application/json'
			}
		});

		const { id } = await response.json();

		data.todos = [...data.todos, {
			id,
			description
		}];

		input.value = '';
	}}
/>

data를 변경할 때에는 페이지를 다시 로드해도 같은 결과를 얻을 수 있는 방식으로 변경해야 합니다.

Next: 기타 핸들러

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<script>
	export let data;
</script>
 
<div class="centered">
	<h1>todos</h1>
 
	<label>
		add a todo:
		<input
			type="text"
			autocomplete="off"
			on:keydown={async (e) => {
				if (e.key !== 'Enter') return;
 
				const input = e.currentTarget;
				const description = input.value;
				
				// TODO handle submit
 
				input.value = '';
			}}
		/>
	</label>
 
	<ul class="todos">
		{#each data.todos as todo (todo.id)}
			<li>
				<label>
					<input
						type="checkbox"
						checked={todo.done}
						on:change={async (e) => {
							const done = e.currentTarget.checked;
 
							// TODO handle change
						}}
					/>
					<span>{todo.description}</span>
					<button
						aria-label="Mark as complete"
						on:click={async (e) => {
							// TODO handle delete
						}}
					/>
				</label>
			</li>
		{/each}
	</ul>
</div>
 
<style>
	.centered {
		max-width: 20em;
		margin: 0 auto;
	}
 
	label {
		display: flex;
		width: 100%;
	}
 
	input[type="text"] {
		flex: 1;
	}
 
	span {
		flex: 1;
	}
 
	button {
		border: none;
		background: url(./remove.svg) no-repeat 50% 50%;
		background-size: 1rem 1rem;
		cursor: pointer;
		height: 100%;
		aspect-ratio: 1;
		opacity: 0.5;
		transition: opacity 0.2s;
	}
 
	button:hover {
		opacity: 1;
	}
</style>
	
initialising