TIL 7주차 fetch 기초

lim1313·2021년 9월 1일
0

부트캠프 TIL

목록 보기
24/49

fetch

URL로 요청하는 걸 가능하게 해 주는 API가 바로 fetch API
fetch API는 Promise의 형식으로 이루어져 있다.

fetch(url)
  .then((response) => response.json()) // 자체적으로 json() 메소드가 있어, 응답을 JSON 형태로 변환시켜서 다음 Promise로 전달
  .then((json) => console.log(json)) // 콘솔에 json을 출력
  .catch((error) => console.log(error)); // 에러가 발생한 경우, 에러

json()

fetch(url)
  .then((response) => response.json()) 

fetch()를 통해 전달받은 response는 HTTP Response이며 JSON이 아니다. 때문에 json() 메소드를 사용하여 resonse body를 json의 object로 변환한다.

이러한 과정을 진행하면 JSON.parse()와 같이 js 객체를 받게 된다.

그렇다면 JSON.pasre()와 response.json()의 차이는 뭘까..?

내가 찾은 답은 아래와 같다.(정확한 답이 아닐 수 있다)


JSON.parse() vs response.json()

stackoverflow json() vs parse()

json()

  • response.json()에는 응답 헤더가 들어가도 바디만 읽어서 불러온다.

  • Body.json() is asynchronous and returns a Promise object that resolves to a JavaScript object.
    : json()은 비동기적이며 프로미스 객체를 리턴한다.

  • the .json() method parses the JSON response into a JS object literal
    : json()은 json 응답을 js 객체리터럴로 parse한다.

parse()

  • JSON.parse()에는 응답(response) 바디만을 넣어야 한다.바디와 헤더가 들어가면 데이터를 읽어오지 못한다

  • JSON.parse() is synchronous can parse a string and change the resulting returned JavaScript object.
    : JSON.parse()는 동기적으로 문자열을 parse할 수 있고, JavaScript 값이나 객체를 생성한다.

profile
start coding

0개의 댓글