본문 바로가기

JavaScript

JavaScript - Axios 이용한 외부 데이터 연동

Axios

: node.js와 브라우저를 위한 Promiss 기반 HTTP 클라이언트

 서버사이드에서는 네이티브 node.js의 http 모듈을 사용하고,

 클라이언트(브라우저)에서는 XMLHttpReauests를 사용

 

설치

node.js 설치 : https://nodejs.org/ko/download

 

다운로드 | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

node.js 설치 확인

C:\>node -v
v18.18.2

C:\>npm -v
9.8.1

 

작업 디렉터리를 생성 후 , 웹서버를 실행

C:\>mkdir react
C:\>cd react

C:\react> npm install -g http-server // => http-server : 웹 페이지에서 사용할 웹 서버

C:\react> npx http-server		// 현재 디렉터리를 웹 루트 디렉터리로 하는 웹 서버를 실행
Starting up http-server, serving ./

http-server version: 14.1.1

http-server settings:
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  http://172.28.0.1:8081
  http://172.18.128.1:8081
  http://192.168.10.1:8081
  http://10.0.0.1:8081
  http://192.168.153.1:8081
  http://192.168.111.1:8081
  http://192.168.0.12:8081
  http://127.0.0.1:8081
Hit CTRL-C to stop the server

브라우저에서 http://localhost:80080 으로 접속

index.html 파일 생성

C:\react> code .

 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello React</h1>
</body>
</html>

** html:5 - HTML5 boilerplate(반복적으로 사용되는 구문) 입력하는 방법 중 하나

실행에 필요한 자바스크립트 라이브러리 추가

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   
    <!-- 실행에 필요한 자바스크립트 라이브러리를 추가 -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

</head>
<body>
    <script>
    </script>
</body>
</html>

 

axios를 이용하여 국가 및 국기 데이터를 가져옴

https://restcountries.com/v3.1/all?fields=name,flags

사용하는 데이터

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   
    <!-- 실행에 필요한 자바스크립트 라이브러리를 추가 -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
</head>
<body>
    <script>
        // axios를 이용해서 국가 및 국기 데이터를 가져옮
        axios
        .get('https://restcountries.com/v3.1/all?fields=name,flags')
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
    </script>
</body>
</html>

데이터를 가공하고 뿌려지는 코드 작성

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   
    <!-- 실행에 필요한 자바스크립트 라이브러리를 추가 -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
</head>
<body>
    <ul>
    </ul>


    <script>
        // axios를 이용해서 국가 및 국기 데이터를 가져옮
        axios
        .get('https://restcountries.com/v3.1/all?fields=name,flags')
        .then(res => {

            res.data.forEach(nf => {		// 가져온 데어터는 res.data 에 들어있음
                const li = `				// forEach를 사용하여 필요한 데이터를 가져옴
                    <li>
                        <img src="${nf.flags.png}" alt="${nf.flags.alt}">
                        <p>${nf.name.common} (${nf.name.official})</p>
                    </li>
                `;
                $('ul').append(li);
            });
        })
        .catch(err => console.log(err));
    </script>
</body>
</html>

728x90