[JavaScript] fetch

노호준·2023년 1월 19일
0

fetch API

  • 사이트에는 정적인 정보, 고정적인 정보가 있음
  • 많은 웹사이트는 동적정보를 업데이트하기위해 요청 api를 씀. fetch api가 대표
  • 원격 url로부터 요청보내고 정보를 담아와서 특정 dom엘리먼트를 업데이트함
  • 비동기로 이뤄지는데, 시간이 소요되는경우 dom에 정보뜨기전까지 로딩창을 띄우기도 함
  • node.js에는 fetch API가 내장모듈로 제공안됨,
  • promise를 리턴함. 똑같이 then쓰되 변수.json()으로 데이터 꺼내야 쓸수있음
async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  let result1 = await fetch(newsURL).then(response => response.json());
  let result2 = await fetch(weatherURL).then(response => response.json());
  return {
    news: result1.data,
    weather: result2
  }
}
if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAsync
  }
}

axios

  • fetch 편한버전, 써드파티이므로 따로 깔아야함

    npm install axios

  • get요청으로 json안하고
import axios from 'axios';

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

POST요청

  • 서버에 데이터보내기위해 사용하는 메서드

    axios.post("url",data)

axios
  .post('https://koreanjson.com/users', { nickName: 'ApeachIcetea', age: '20' })
  .then((response) => {
    const { data } = response;
    console.log(data);
  })
  .catch((error) => console.log(error));

비동기 추가팁

복습: spread, 구조분해할당, async/await > 암기

  • JSON.parse , .json() => JSON포맷의 데이터를 자바스크립트의 데이터 변환
    .json은 fetch의 response에서 데이터 꺼내올수 있다.
  • npm install 하면 해당 프로젝트에서만 라이브러리 설치됨.
  • fetch에서 .json()은 response에서 데이터를 뽑아왔기 때문에

0개의 댓글

관련 채용 정보