fetch API

지은·2022년 9월 27일
0

JavaScript

목록 보기
34/42

fetch API

fetch API를 이용해 원격 URL로부터 실시간 정보를 받아올 수 있다.
이러한 작업은 비동기로 이루어진다.

기본적인 Fetch 요청

fetch('https://koreanjson.com/posts/1')
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.log(error));

위의 코드를 한 줄 한 줄 해석해보면...
1. fetch() 메소드를 이용해 URL로부터 response를 받는다.
2. response를 받아, json() 메소드를 이용해 객체를 추출한다.
3. 추출한 객체를 콘솔로그에 출력한다.
4. 에러가 발생하면 에러를 콘솔로그에 출력한다.


fetch()

fetch(url) : 리소스의 경로를 매개변수로 받아 정보를 받아오는 메소드

fetch() 메소드로 URL에서 정보를 받아와서, 그 응답(response)를 콘솔 로그에 출력해보면...

fetch('https://koreanjson.com/posts/1')
  .then((response) => console.log(response));

➡️ fetch()Promise 객체를 반환하고,
이 Promise는 이행되었을 때 Response 객체를 반환한다.

Response 객체

Response 객체는 HTTP response를 가지고 있으며 우리가 얻어야 할 정보인 JSON 본문(body)(...)으로 나타난다. 이때 body에 접근하려면 어떻게 해야할까?

➡️ json() 메소드를 이용해 Response로부터 JSON을 추출해야 한다.

fetch('https://koreanjson.com/posts/1')
  .then((response) => response.json())

response.json()

response.json()Promise 객체를 반환하고,
이 Promise는 이행되었을 때 JSON을 JavaScript 객체로 변환시켜 반환한다.

따라서, response.json()의 결과값을 콘솔 로그에 출력해보면 아래의 객체가 반환되는 것을 확인할 수 있다.

fetch('https://koreanjson.com/posts/1')
  .then((response) => response.json())
  .then((json) => console.log(json))


예시 1) fetch, then 이용

news URL, weather URL에서 뉴스와 날씨 정보를 받아와서
하나의 객체 안에 {{news: ...}, {weather: ...}} 넣어서 반환하는 함수

const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';

function getNewsAndWeather() {
  return fetch(newsURL)
    .then((response) => response.json())
  	.then((json) => json.data)
    .then((news) => {
      return fetch(weatherURL)
      .then((response) => response.json())
      .then((weather) => {
        return {news, weather} // 객체 구조 분해 할당
      })
  })
}

객체의 구조 분해 할당 (Destructuring Assignment)

기억이 가물가물해서 다시 정리하고 넘어간다 😅

const gg = {name: 'GG', age: 12};
const bella = {name: 'Bella', age: 10}

const obj = {gg, bella};
obj; // {gg: {...}, bella: {...}}

객체 구조 분해 할당을 이용하면 obj.key = value 형식으로 귀찮게 객체 안에 키와 값을 추가할 필요 없다.


예시 2) fetch, then 이용

function getNewsAndWeatherAll() {
  const news = fetch(newsURL).then((response) => response.json()).then((json) => json.data)
  const weather = fetch(weatherURL).then((response) => response.json())

  return Promise.all([news, weather])
  .then(([news, weather]) => ({news, weather}))
} // 여기서 매개변수를 꼭! [] 배열로 받아야 한다.

예시 3) async, await 이용

async function getNewsAndWeatherAsync() {
  const news = await fetch(newsURL).then((res) => res.json()).then((json) => json.data)
  const weather = await fetch(weatherURL).then((res) => res.json()).then((json) => json)

  return {news, weather}
}

헷갈리는 용어 정리

JSON.parse()

JSON.stringify()

.json()

profile
개발 공부 기록 블로그

0개의 댓글