차근차근

fetch API로 폼 데이터 전송하기|JavaScript로 배우는 기본부터 실전까지

디어노미 2025. 4. 22. 12:26
반응형

📤 fetch API로 폼 데이터 전송하기|JavaScript로 배우는 기본부터 실전

안녕하세요, 퍼블리셔 노미입니다!
지난 시간에는 HTML 폼을 만들고 JavaScript로 유효성 검사까지 적용했었죠?
그럼 이제 남은 한 가지! 바로 “사용자가 입력한 데이터를 서버로 보내는 것”입니다. 이때 사용하는 도구가 바로 fetch API에요.


이 글에서는 fetch API의 기초 문법부터 실전 활용법, JSON 전송, 응답 처리, 에러 처리까지 **폼 데이터 전송에 필요한 모든 핵심 지식**을 정리해서 알려드릴게요.


📌 fetch API란?

fetch API는 브라우저에서 비동기적으로 네트워크 요청을 보내고 응답을 받기 위한 표준 API입니다.
쉽게 말해, JavaScript를 이용해 서버와 데이터를 주고받을 수 있게 해주는 도구입니다.


fetch("url", {
  method: "POST",
  headers: {},
  body: {}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("에러 발생:", error));

🧾 HTML 폼 기본 구조


<form id="contactForm">
  <input type="text" id="name" placeholder="이름" required>
  <input type="email" id="email" placeholder="이메일" required>
  <textarea id="message" placeholder="내용"></textarea>
  <button type="submit">보내기</button>
</form>

이제 이 폼을 fetch로 JavaScript에서 직접 제어해볼게요.


🛠️ fetch API로 폼 데이터 보내는 방법

① submit 이벤트 가로채기


const form = document.getElementById("contactForm");

form.addEventListener("submit", function(e) {
  e.preventDefault(); // 기본 제출 막기
});

② 입력값 수집


const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
const message = document.getElementById("message").value;

③ JSON 형태로 변환


const data = {
  name: name,
  email: email,
  message: message
};

④ fetch POST 요청 보내기


fetch("https://example.com/api/contact", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
  alert("전송 성공!");
})
.catch(error => {
  console.error("에러 발생:", error);
});

🔁 FormData 객체로 전송하는 방법

파일 업로드나 간단한 전송에는 FormData 객체도 자주 사용됩니다.


const formData = new FormData(form);

fetch("/upload", {
  method: "POST",
  body: formData
})
.then(res => res.text())
.then(result => console.log(result));

주의: FormData 방식은 Content-Type 헤더를 자동으로 설정하므로 따로 지정하지 않아야 해요.


📡 JSON vs FormData 비교

항목 JSON 방식 FormData 방식
형식 application/json multipart/form-data
파일 전송 불가 가능
간결성 높음 낮음
프론트 제어 용이함 제한적

✅ 응답(Response) 처리하기


fetch("/api")
  .then(res => {
    if (!res.ok) {
      throw new Error("서버 오류");
    }
    return res.json();
  })
  .then(data => {
    console.log("결과:", data);
  })
  .catch(err => {
    alert("요청 실패: " + err.message);
  });

💡 UX를 위한 처리 팁

  • 전송 중 로딩 상태 표시
  • 성공/실패 메시지 폼 하단에 출력
  • 버튼 비활성화 처리로 중복 요청 방지

button.disabled = true;
button.textContent = "전송 중...";

fetch(…)
  .then(…)
  .finally(() => {
    button.disabled = false;
    button.textContent = "보내기";
  });

🧪 실전 예제: 문의폼 전송


<form id="form">
  <input type="text" id="name" placeholder="이름">
  <input type="email" id="email" placeholder="이메일">
  <textarea id="msg" placeholder="문의 내용"></textarea>
  <button type="submit">문의하기</button>
  <p id="result"></p>
</form>

<script>
document.getElementById("form").addEventListener("submit", function(e) {
  e.preventDefault();

  const data = {
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    msg: document.getElementById("msg").value
  };

  fetch("https://example.com/contact", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  })
  .then(res => res.json())
  .then(result => {
    document.getElementById("result").textContent = "문의가 접수되었습니다.";
  })
  .catch(err => {
    document.getElementById("result").textContent = "전송 실패!";
  });
});
</script>

📚 마무리하며

오늘 배운 fetch API와 폼 전송 방식은 웹 프로젝트에서 아주 많이 사용됩니다.
유효성 검사와 함께 fetch를 활용하면, 여러분도 실전 웹 서비스를 충분히 구현할 수 있어요!

다음 편에서는 AJAX 방식으로 비동기 통신 처리하기JSON 서버를 직접 띄우는 방법을 이어서 알려드릴게요.


#fetchAPI #폼데이터전송 #JavaScript실전 #프론트엔드입문 #웹퍼블리싱 #JSON전송 #FormData활용 #폼구현노하우 #퍼블리셔노미

반응형