본문 바로가기
Coding/Javascript

Javascript - fetch api(1)

by z쿳쿳z 2020. 8. 4.
728x90
반응형

fetch api는 네트워크 통신을 통해 리소스 취득을 위한 인터페이스 이다.

 

fetch(url, options)

 

하단에서 요청하는 방식은 GET 요청일 때 사용하는 방식이다.

 

fetch를 리소스에서 데이터를 가지고 오지만, 결과를 확인해 보면 fetch는 promise 객체를 받아온다. 그렇기 때문에 받아온 데이터를 우리가 필요한 정보로 가공 할 수 있도록 코드를 해야한다.

promise 객체를 받아오기 때문에, promise 메소드를 사용할 수 있다.

주로 사용하는방법은

fetch(url, options)

 .then(res=>res.json())

 .then(data=>callback(data))

이렇게 많이 사용을 한다.

(기본적으로 options를 주지 않으면 method는 get요청을 한다.)

codestates 과제에서 했던 예제를 사용해 보면(.json()은 내장 메소드로 제공된다.)

 첫번째 fetch에서 newsURL에서 데이터를 받아오고, 이 데이터를 바로 json()을 사용해서 JSON data를 볼 수 있도록 만들어준다.

 두번째 fetch에서 weatherURL에서 데이터를 받아고, 이 데이터를 바로 json()을 사용해서 JSON data를 볼 수 있도록 만들어서 새로운 객체에 넣어준다.

var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';

function getNewsAndWeather() {
  return fetch(newsURL)
  .then(nresponse => nresponse.json())
  .then(njson =>{
    return fetch(weatherURL)
    .then(wresponse => wresponse.json())
    .then((wjson)=>{
      let result = {};
      result.news= njson.data;
      result.weather =wjson;
      return result;
    })  
  })
};

 

위코드를 console에서 확인하면 다음과 같다.(server를 실행 시키고 server에 있는 data를 받아 온 결과)

 

#Javascript#codestates#fetch#promise#then

728x90
반응형

'Coding > Javascript' 카테고리의 다른 글

TypeError: x is not a function  (0) 2021.07.14
Javascript - fetch api(2)  (0) 2021.03.04
Javascript - 비동기 처리(3)(async await)  (0) 2020.07.17
Javascript - 비동기처리(2)(Promise)  (0) 2020.07.16