less than 1 minute read

fetch

fetch 함수는 HTTP 요청 전송 기능을 제공하는 클라이언트 사이드 Web API다. fetch함수는 HTTP 응답을 나타내는 Response 객체를 래핑한 Promise 객체를 반환한다. 반환값이 프로미스이므로 then을 통해 프로미스가 resolve한 Response 객체를 전달받을 수 있다.


다음 예제를 개발자 도구에서 요청해보자

fetch('https://jsonplaceholder.typicode.com/todos/1')
	.then(response => console.log(response)); 

fetch1

Response.prototype에는 Response 객체에 포함되어 있는 HTTP 응답 몸체를 위한 다양한 메서드를 제공한다.

fetch2


GET 요청

GET 메서드는 특정 리소스의 표시를 요청합니다. GET을 사용하는 요청은 오직 데이터를 받기만 합니다.

request.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(todos => console.log(todos))
  .catch(err => console.error(err));
// {userId: 1, id: 1, title: "delectus aut autem", completed: false}


POST 요청

POST 메서드는 특정 리소스에 엔티티를 제출할 때 쓰입니다. 이는 종종 서버의 상태의 변화나 부작용을 일으킵니다.

request.post('https://jsonplaceholder.typicode.com/todos', {
  userId: 1,
  title: 'JavaScript',
  completed: false
}).then(response => response.json())
  .then(todos => console.log(todos))
  .catch(err => console.error(err));
// {userId: 1, title: "JavaScript", completed: false, id: 201}


PATCH 요청

PATCH 메서드는 리소스의 부분만을 수정하는 데 쓰입니다.

request.patch('https://jsonplaceholder.typicode.com/todos/1', {
  completed: true
}).then(response => response.json())
  .then(todos => console.log(todos))
  .catch(err => console.error(err));
// {userId: 1, id: 1, title: "delectus aut autem", completed: true}


DELETE 요청

DELETE 메서드는 특정 리소스를 삭제합니다.

request.delete('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(todos => console.log(todos))
  .catch(err => console.error(err));
// {}


더 자세한 내용은 HTTP 요청 메서드Fetch 사용법을 참고하자.