[Js] Fetch api

DongHyeon Jung·2022년 10월 16일
0

Javascript

목록 보기
3/5
post-thumbnail

Fetch api

What is fetch?

Fetch API 는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공한다
Fetch API가 제공하는 전역 fetch()메서드로 네트워크의 리소스를 쉽게 비동기적으로 가져올 수도 있습니다.
다시말해,
fetch함수로 원격 API를 호출할 수 있다.**
라이브러리의 도움없이도 브라우저에서 내장된 fetch()함수를 이용할 수 있다.

When we use fetch()?

  • 데이터를 가져오고 싶을 때
  • JSON, XML 형식의 파일을 불러오고 싶을 때
  • 웹 서버에 데이터를 전달하고 싶을 때
  • 웹 서버 연동 프로그램을 만들고 싶을 때

How we use fetch?

fetch('/readme.txt')
    .then(response => response.text())
    .then(data => console.log(data));

fetch()함수는 첫번째 인자로 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"
}

예제를 통해 알아보자

fetch('../todos/jayden.json').then((response) => {
  // 😃 resolved success case
  console.log('resolved', response);
  return response.json();
}).then(data => {
  console.log(data);
}).catch((err) => {
  // 🤔 rejected error case
  console.log('rejected', err); 
});
  1. fetch로 데이터를 가져온다.
  2. 응답을 받는다
  3. return한다
fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));

Reference

https://www.daleseo.com/js-window-fetch/
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

0개의 댓글