
Form Submit
HTML form을 사용해 서버로 데이터를 전송하는 전통적인 방식입으로, 사용자가 폼을 작성한 후 submit 버튼을 클릭하면 폼의 데이터를 서버로 보낸다.
<form action="/submit" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit">Submit</button>
</form>
Fetch
JavaScript API로, 비동기적으로 서버에 데이터를 전송하는 방식이다. fetch는 페이지를 새로 고침하지 않고 데이터를 서버로 보내거나 받아올 수 있는 방법을 제공한다.
async function submitForm(event) {
event.preventDefault();
const data = { username, password };
try {
const response = await fetch('http://localhost:3000/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error('Failed to fetch: ' + response.statusText);
}
const result = await response.json();
responseMessage = result.message;
console.log('Server Response:', result);
} catch (error) {
console.error('Error:', error);
responseMessage = 'Error occurred while submitting the form.';
}
}