본문 바로가기

Learn/Javascript

fetch API

시작하기전에

 

전에 배웠던 것중에 Promise가 어떻게 작동하는지에 대해 다시 복습

Promise에는 3가지 작동원리가 존재

  • 대기(pending): 이행하지도, 거부하지도 않은 초기 상태.
  • 이행(fulfilled): 연산이 성공적으로 완료됨.
  • 거부(rejected): 연산이 실패함.

그리고 console.log를 찍었을 때 어떤 형태를 반환하는지에 대해 숙지

아래풀이가 이해되지 않을 때 다시보기

 

 

fetch API

HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공

-> 특정 url을 불러오는 역할을 하며 비동기적인 역할을 한다. 따라서 promise를 리턴한다.

-> fetch의 기본형태

// 1번째
fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));
  
// 2번째
let url = 'http://example.com/movies.json'

fetch(url)
  .then((response) => response.json())
  .then((data) => console.log(data));

 

fetch 사용법

 

.then chaining

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

function getNewsAndWeather() {
  // TODO: fetch을 이용해 작성합니다
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
  fecth(newsURL).then((res)=> res.json()).then({data : news} => {   // (news를 consol.log(news) 를 사용했을 때 객체 안에 담겨있다.)구조분해할당-> data라는 키의 value(값)을 가져와야 하기 때문에
  	return fetch(weatherURL) .then(res => res.json()).then(weather => {  //weather consol.log(weather) 를 사용했을 때 바로 가져올 수 있기 때문에 바로 사용
    	return {
        	news: news,                  // 같은 이름이라 news 로만 써도된다.
            weather : weather			// 같은 이름이라 weather 로만 써도된다.
        }
    })
  ])
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeather
  }
}

 

 

Promise.all

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  return Promise.all([fetch(newsURL), fetch(weatherURL)])
  .then(([res1,res2]) => {
  	return promise.all([res1.json(), res2.json()]).then(([{data : news}, weather])=>{
    	return { news, weather}
    })
  })
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAll
  }
}

 

async/await

async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  const {data : news} = await fetch(newsURL).then((res) => res.json())
  const weather = await fetch(weatherURL).then((res) => res.json())
  return {news , weather}
}
if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAsync
  }
}

 

 

Axios

 

브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리

 

GET 요청

GET 요청은 일반적으로 정보를 요청하기 위해 사용되는 메서드

axios.get("url"[,config])

 

POST 요청

POST 요청은 서버에게 데이터를 보내기 위해 사용되는 메서드

 

axios.post("url"[, data[, config]])

 

 

AXIOS를 쓰기 위해 fetch를 배웠고 fetch를 쓰기위해 promise를 배웠고 promise를 배우기 위해 비동기를 배웠다.

 

최종적으론 AXIOS를 사용한다고 한다.

 

fetch은 .json()으로 javascript로 읽기 위해 문서전환이 필요하지만

AXIOS는 npm 설치로 인해 바로 javascript로 문서를 읽을 수 있기에 훨씬 간단하다.

 

axios
  .get('https://koreanjson.com/users/1')
  .then((response) => {
    console.log(response);
    const { data } = response;
    console.log(data);
  })
  .catch((error) => console.log(error));

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

JSON  (0) 2023.02.14
재귀함수  (0) 2023.02.13
Node:fs 모듈 진행하면서 새로 배운 개념  (0) 2023.01.18
동기 / 비동기  (0) 2023.01.17
프로토타입  (0) 2023.01.13