📚 상세 배경 설명: fetch와 HTTP Method

fetch는 JavaScript에서 네트워크 요청을 보낼 때 가장 많이 쓰이는 함수예요.
웹페이지가 서버랑 데이터를 주고받을 때 사용하는 기본 도구라고 보면 됩니다.

HTTP Method는 요청의 ‘목적’을 알려주는 역할을 하는데, fetch에서는 이 메서드를 옵션으로 지정해서 서버에 어떤 작업을 할지 알려줘요.

예를 들어, POST 메서드는 “새 데이터를 서버에 만들어주세요” 요청이고, GET은 “데이터 좀 보여주세요” 요청이에요.


💻 실무 예제 코드: fetch 사용법 - POST, PUT, PATCH, DELETE

javascript
// POST - 새 데이터 생성
fetch('https://api.example.com/users', {
  method: 'POST',  
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => console.log('Created:', data))
.catch(error => console.error('Error:', error));


// PUT - 기존 데이터 전체 수정
fetch('https://api.example.com/users/123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John Doe', age: 31 })
})
.then(response => response.json())
.then(data => console.log('Updated:', data))
.catch(error => console.error('Error:', error));


// PATCH - 기존 데이터 일부 수정
fetch('https://api.example.com/users/123', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ age: 32 })
})
.then(response => response.json())
.then(data => console.log('Partially Updated:', data))
.catch(error => console.error('Error:', error));


// DELETE - 데이터 삭제
fetch('https://api.example.com/users/123', {
  method: 'DELETE'
})
.then(response => {
  if (response.ok) {
    console.log('Deleted successfully');
  } else {
    console.error('Failed to delete');
  }
})
.catch(error => console.error('Error:', error));

 

⚠️ 자주 하는 실수와 해결법 

 

💡 초보자 팁!

  • fetch 기본 구조는 URL + 옵션 객체(method, headers, body 등)
  • 서버가 JSON 데이터를 받는다고 하면 headers와 body를 꼭 맞게 설정해야 해요
  • 비동기라 결과 받기 전엔 바로 콘솔에 찍히지 않으니 .then()이나 async/await 꼭 써요

🚀 실력자 팁!

  • 에러 핸들링을 강화하려면 HTTP 상태 코드별 분기 처리 추천
  • async/await로 가독성 좋게 코드 작성하면 유지보수 편해져요
  • 대용량 POST 요청 시 body를 스트리밍 처리하거나, 여러 요청으로 나누는 것도 고려해 보세요
  • CORS 정책 이해와 대응도 fetch 활용에 필수!

+ Recent posts