개발자 첫걸음/The WEb Developer BootCamp 2022

Section 28: AJAX와 API

프로아마추어 2022. 4. 30. 19:20

1. AJAX 개요

  • 기존 요청 방식은 client의 특정 이벤트로부터 요청을 받은 서버가 
    html, css 그리고 JavaScript를 통해 새로운 웹 페이지를 출력해주는 방식이었다.
  • AJAX의 경우에는 JavaScript 코드로 요청을 받고 그 결과에 대한 data를 응답 받는다.
    이는 개발자도구 NetWork 탭을 통해 확인할 수 있다.
  • 앞으로 formatting, data를 받기 위한 API, JavaScript를 통한 요청 방법을 알아볼 것이다.

 

2. APIs 개요

  • 웹 개발자들이 언급하는 API 보통 WebAPI를 지칭한다.
  • WebAPI는 HTTP를 기반으로 하는 인터페이스이며 다른 Application이나 database로 가는 진입로라고 볼 수 있다.
  • API의 종류는 무수히 많다. 단순히 정보를 불러오거나 문자를 발송하거나 채팅 봇을 만들 수도 있다.

 

3. JSON이란?

  • API로부터 받은 데이터의 format 형태에는 XML과 JSON이 있다.
  • 현재 대부분의 API JSON을 사용하며 JavaScript 객체 유형을 사용한다.
  • JSON.parse() - JSON 문자열을 JavaScript 값이나 객체로 변환
  • JSON.stringify() - JavaScript 값이나 객체를 JSON 문자열로 변환. undefined 값은 null로 바꿔준다.

 

4. Postman 사용하기

  • API 테스트, 작동 원리 확인을 위해 요청을 받을 수 있는 debugging tool이다.
  • status 코드를 확인해보자
    • 2로 시작하는 코드는 좋은 의미를 가진다.
    • 3으로 시작하는 코드는 redirect를 의미한다.
    • 4로 시작하는 코드는 client 에러를 의미한다.
    • 5로 시작하는 코드는 server 에러를 의미한다.
  • header를 확인해보자
    • key-value 형태를 가진다.
    • 통신의 요청, 응답에 대한 정보를 가지고 있다.

 

5. queryString 및 header query

  • queryString - 요청 시 추가 정보를 요청할 때 사용한다.
    • url 끝에 붙는 것이 특징이다. url끝에 물음표(?)가 나온다면 queryString 시작을 알리는 것이다.
    • 여러 queryString을 매개 변수로 받는다면 and(&)로 묶어준다.
  • /search/shows -> base url
  • /search/shows?q=:query -> base url + queryString
  • API가 필요로 한다면 요청에도 header를 포함할 수 있다.

 

6. XHR 객체 만들기

  • 오래된 초기 요청 방식이며 promise를 지원하지 않아 콜백 함수를 사용해야 한다.

예제: XML 객체 만들기

const req = new XMLHttpRequest();

예제: XML 

// 응답 성공 콜백함수
req.onload = function () {
  console.log('ALL DONE WITH REQUEST!!!');
  const data = JSON.parse(this.responseText);
  console.log(data[0].score);
};

// 응답 실패 콜백함수
req.onerror = function () {
  console.log('ERROR!');
};

// API에 GET방식으로 통신 요청
req.open('GET', 'https://api.tvmaze.com/search/shows?q=girls');
req.send();

 

7. Fetch API

  • JavaScript로 요청하는 방식.
  • promise를 지원한다

예제: Fetch로 API 응답 받기(promise)

fetch('https://api.tvmaze.com/search/shows?q=girls')
  .then(res => {
    // header 정보만 담겨있다.
    console.log('RESPONSE, WAITING TO PARSE..', res);
    return res.json(); // promise(body)를 return 한다.
  })
  .then(data => console.log('DATA PARSED...', data))
  .catch(err => {
    console.log('ERROR', err);
  });

예제: Fetch로 API 응답 받기(async)

const fetchTvProgram = async () => {
  try {
    const res = await fetch('https://api.tvmaze.com/search/shows?q=girls');
    const data = await res.json();
    console.log(data);
  } catch (e) {
    console.log('ERROR!', e);
  }
};

 

8. Axios 개요

  • fetch기반으로 API 통신을 간편하게 할 수 있는 라이브러리이다.

https://axios-http.com/kr/docs/intro/

 

시작하기 | Axios Docs

시작하기 브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리 Axios란? Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코

axios-http.com

예제: axios로 API 응답 받기(promise)

axios
  .get('https://api.tvmaze.com/search/shows?q=girls')
  .then(res => {
    console.log(res.data[0].score);
  })
  .catch(err => {
    console.log('EEROR!', err);
  });

예제: axios로 API 응답 받기(async)

const fetchTvProgramScore = async () => {
  try {
    const res = await axios.get('https://api.tvmaze.com/search/shows?q=girls');
    console.log(res.data[0].score);
  } catch (e) {
    console.log('ERROR!', e);
  }
};

fetchTvProgramScore();

 

9. Axios로 헤더 세팅하기

  • API 중 header를 요구하는 경우가 있다.
// index.html
<h1>Click to get new jokes!</h1>
<button>Click me!</button>
<ul id="list"></ul>
// app.js

const jokes = document.querySelector('#list');
const button = document.querySelector('button');

const addNewJoke = async () => {
  const jokeText = await getDadJoke();
  console.log(jokeText);
  const newLI = document.createElement('li');
  newLI.append(jokeText);
  jokes.append(newLI);
};

const getDadJoke = async () => {
  try {
	// header 값을 세팅해준다.
    const config = { headers: { Accept: 'application/json' } };
    const res = await axios.get('https://icanhazdadjoke.com/', config);
    return res.data.joke;
  } catch (e) {
    console.log('ERROR', e);
  }
};

button.addEventListener('click', addNewJoke);

 

10. TV프로그램 검색 앱

// index.html
<h1>TV Show Search</h1>
<form id="serachForm">
  <input type="text" name="query" placeholder="tv show title search" />
  <button>SEARCH</button>
  <div id="image-container"></div>
</form>
// app.js

const form = document.querySelector('#serachForm');
const imgBox = document.querySelector('#image-container');

form.addEventListener('submit', async function (e) {
  e.preventDefault();
  const searchTerm = form.elements.query;
  // parameter 값이나 header 관련 값들을 객체에 추가할 수 있다.
  const config = { params: { q: searchTerm.value } };
  const res = await axios.get(`https://api.tvmaze.com/search/shows`, config);
  makeImages(res.data);
  searchTerm.value = '';
});

const makeImages = showLists => {
  for (let showList of showLists) {
    if (showList.show.image) {
      const img = document.createElement('img');
      img.src = showList.show.image.medium;
      imgBox.append(img);
    }
  }
};