JavaScript

fetch

Hyunsoo_Kim 2023. 10. 7. 14:07

fetch



네트워크 요청을 보내거나, 응답을 처리하는 웹 API

 


 

GET 요청


window.onload = () => {
  const response = fetch("https://learn.codeit.kr/api/members");
}

console.log(response);

window.onload = () => {
  fetch("https://learn.codeit.kr/api/members")
    .then((promiseResult) => { console.log(promiseResult.json()); });
}

1. 첫번째 인자로 앤드포인트를 넣는다.

2. 선택적으로 두번째 인자에 method와 headers 프로퍼티를 가진 객체를 넣을 수 있다.

3. fetch는 promise 객체를 반환하며, [[PromiseResult]]에 json형식으로 된 리스폰스 객체를 갖고 있다.

 

POST 요청


window.onload = () => {
  const requestBody = {
    name: "Lee",
    email: "Lee@codeit.com",
    department: "engineering"
  }

  const response = fetch("https://learn.codeit.kr/api/members", {
    method: "POST",
    body: JSON.stringify(requestBody),
    headers: {
      "Content-Type": "application/json"
    }
  });
}

1. 첫번째 인자에 POST 요청 할 앤드포인트가 들어간다.

2. 두번째 인자에 method 프로퍼티와, 서버에 추가할 리퀘스트 바디, 선택적으로 headers 프로퍼티를 포함한 객체를 넣는다.

 

PUT 요청


window.onload = () => {
  const requestBody = {
    name: "Lee",
    email: "Lee@codeit.com",
    department: "engineering"
  }

  const response = fetch("https://learn.codeit.kr/api/members/7", {
    method: "PUT",
    body: JSON.stringify(requestBody),
    headers: {
      "Content-Type": "application/json"
    }
  });
}

1. 첫번째 인자에 앤드포인트가 들어간다.

2. 두번째 인자에 method 프로퍼티, 수정할 리퀘스트 바디, 선택적으로 header 프로퍼티를 포함한 객체를 넣는다.

 

DELETE 요청


window.onload = () => {
  const response = fetch("https://learn.codeit.kr/api/members/2", {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json"
    }
  });
}

1. 첫번째 인자에 앤드포인트가 들어간다.

2. 두번째 인자에 method 프로퍼티, 선택적으로 headers 프로퍼티를 포함한 객체를 넣는다.

 

then



응답받은 데이터를 처리

window.onload = () => {
  const response = fetch("https://learn.codeit.kr/api/members");
}

console.log(response)

1. 요청 받은 데이터는 Promise 객체로 되어있어, 바로 사용할 수 없다 (Promise : https://dog-foot.tistory.com/65)

2. promise 의 프로토타입의 then 메서드로 Promise 객체를 조작할 수 있다.

 

window.onload = () => {
  const response = fetch("https://learn.codeit.kr/api/members");
  
  const result = response.then(res => res.json());
}

console.log(result)

1. then 메서드의 콜백함수의 매개변수는 then메서드를 사용한 Promise 객체의 [[PromiseResult]] 값이다.

2. then 메서드는 콜백함수의 return값을 [[PromiseResult]] 로 가지는 Promise 객체를 반환한다.

3. 만약 콜백함수가 Promise 객체를 반환한다면, then은 콜백함수가 반환하려는 것을 그대로 반환한다.