Form Submit vs Fetch

혜진·2025년 1월 21일
post-thumbnail

Form Submit vs Fetch

Form Submit

HTML form을 사용해 서버로 데이터를 전송하는 전통적인 방식입으로, 사용자가 폼을 작성한 후 submit 버튼을 클릭하면 폼의 데이터를 서버로 보낸다.

form 특징

  • 자동 처리: form submit은 브라우저가 자동으로 폼 데이터를 처리하고 서버로 보낸다.
  • GET 또는 POST 요청: GET 또는 POST 메서드로 데이터를 전송한다. 이는 form 태그의 method 속성에 의해 결정된다.
  • 페이지 리로드: 서버로 요청을 보내면 페이지가 새로 고쳐지거나 리디렉션될 수 있다.
  • 데이터 포맷: 폼 데이터는 application/x-www-form-urlencoded 또는 multipart/form-data (파일 업로드의 경우)로 전송된다.

📑 form 예제

<form action="/submit" method="POST">
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">Submit</button>
</form>

Fetch

Fetch

JavaScript API로, 비동기적으로 서버에 데이터를 전송하는 방식이다. fetch는 페이지를 새로 고침하지 않고 데이터를 서버로 보내거나 받아올 수 있는 방법을 제공한다.

Fetch 특징

  • 비동기 처리: fetch는 비동기적으로 작동하여 페이지를 새로 고침하지 않고도 데이터를 서버와 교환할 수 있다.
  • 세부적인 제어: 요청 헤더, 메서드, 본문 등을 매우 세밀하게 제어할 수 있다.
  • 데이터 포맷: fetch를 사용할 때는 JSON, form-data, 텍스트 등 다양한 형식으로 데이터를 전송할 수 있다. Content-Type을 명시적으로 지정할 수 있다.
  • 리로드 없음: 폼 제출과 달리 페이지 리로드 없이 데이터를 처리할 수 있다.

📑 form 예제

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.';
    }
  }

0개의 댓글