728x90
반응형

 

◾ fetch( ) 함수

fetch('api 주소')
  .then(res => res.json())
  .then(res => {
    // data를 응답 받은 후의 로직
  });
fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));

- 첫번째 인자로 URL

- 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환

- 반환된 객체는 API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고

- 실패했을 경우에는 예외(error) 객체를 reject함

 

 

◾ 예시

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data));

이 메서드를 호출하면 응답(response)객체로 부터 JSON 포멧의 응답 전문을 자바스크립트 객체로 변환하여 얻을 수 있음

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"
}

 

 

 

 

 

[출처]

https://www.daleseo.com/js-window-fetch/

728x90
반응형