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"
}
[출처]
728x90
    
    
  반응형
    
    
    
  'Coding With Jina > JavaScript' 카테고리의 다른 글
| [Node.js] 간단하게 Node와 NPM을 최신 버전으로 업데이트하기 (0) | 2024.04.08 | 
|---|---|
| [자바스크립트] 동기와 비동기 차이점 (2) | 2023.02.03 | 
| [자바스크립트] Ajax 정리 (0) | 2022.11.16 | 
| [자바스크립트] Array filter( ) 함수 (0) | 2022.11.12 | 
| [자바스크립트/ES6] for...of 문 / 배열객체마다 반복되는 실행문 (0) | 2021.09.03 |