[Web] Axios 와 API Call

장유진·2023년 7월 14일
0

Web Development

목록 보기
2/5

Axios란?

웹 페이지에서 데이터를 요청하기 위해서는 서버와 통신을 해야 하는데요, Axios는 개발자가 손쉽게 HTTP 요청을 할 수 있도록 하는 JavaScript 라이브러리입니다. Promise API를 기반으로 동작하며 웹 브라우저 혹은 Node.js 환경에서 사용됩니다.

Axios를 사용하는 이유

  1. 직관적으로 사용할 수 있는 쉬운 사용법 + 다양한 프레임워크 라이브러리와의 호환성
  2. Promise 기반 접근 방식 : Axios는 Promise 패턴을 사용하여 비동기적으로 HTTP 요청을 처리합니다.
  3. Axios 인스턴스 : 인스턴스로 만들어 사용하면 요청을 보낼 때마다 필요한 설정들을 추가로 작성하지 않아도 됩니다. (ex. 여러 API 엔드포인트로 요청을 보낼 때, 기본 헤더와 인증 토큰 또는 인터셉터를 설정해야 할 때 사용할 때)
  4. 요청(Request) 및 응답(Response) 인터셉터 : Axios는 then이나 catch로 처리 되기 전에 요청과 응답을 가로채서 부가적인 작업을 할 수 있게 도와주는 인터셉터 기능을 지원합니다.
  5. JSON 변환 : Axios는 자동으로 요청 및 응답 데이터를 JSON 데이터로 변환해줍니다.

Axios 시작하기

설치

npm install axios
 
yarn add axios 

Axios로 HTTP 요청하기

Get 요청

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Post 요청

axios.post('https://api.example.com/data', {name: 'geniee' })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

// data를 객체 형식으로 만들었다면, 다음과 같은 형식으로 post 요청을 할 수 있습니다.

const data = {
	name: 'geniee'
}
 
axios.post('https://api.example.com/data', data)

Put 요청

axios.put('https://api.example.com/data/1', { name: 'geniee1220' })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Delete 요청

axios.delete('https://api.example.com/data/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Request / Response 다루기

인스턴스를 사용하지 않는 일반적인 패턴에서의 요청에 헤더와 Content-Type을 어떻게 설정하는지 , 응답에서 어떤 값들을 확인하는지 설명합니다.

요청 헤더 설정

axios.get('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json'
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

응답 확인

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.status); // HTTP 상태 코드를 확인할 수 있습니다.
    console.log(response.headers); // 응답값의 헤더를 확인할 수 있습니다.
    console.log(response.data); // 응답값 데이터를 확인할 수 있습니다. 
  })
  .catch(error => {
    console.error(error);
  });

❗️ Axios는 HTTP 코드가 2xx이 아니라면(404, 500, 503 등등…) 에러로 처리합니다.

Axios Instance와 Interceptors

Instance

요청이나 응답을 할 때마다 추가해주어야 하는 기본 설정을 Instance로 묶어놓고 사용할 수 있습니다.

Instance 사용하지 않았을 때의 코드입니다. 각 요청마다 필요한 header를 반복해서 적어주고 있는 것을 확인할 수 있습니다.

axios.get('https://api.example.com/data', {
    headers: {
      Authorization: 'Bearer token',
      'Content-Type': 'application/json',
    },
  })
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });

axios.get('https://api.example.com/post', {
    headers: {
      Authorization: 'Bearer token',
      'Content-Type': 'application/json',
    },
  })
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });

Instance 사용했을 때의 코드입니다.

모든 요청에 사용하기 때문에 먼저 별도의 파일에서 인스턴스를 분리해서 정의합니다.

import axios, { AxiosInstance } from 'axios';

const baseURL = 'http://localhost:3000';

export const instance: AxiosInstance = axios.create({
  baseURL: baseURL,
  headers: { 'Content-Type': 'application/json' },
  withCredentials: true,
});

export default instance;

사용할 때는, axios의 위치에 내가 정의한 인스턴스의 이름을 적어줍니다.

Instance를 사용했을 때는 각 요청마다 반복적으로 사용됐던 header 구문이 사라진 것을 확인할 수 있습니다.

import { instance } from '../api'

instance.get('https://api.example.com/data')
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });

instance.get('https://api.example.com/post')
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });

Interceptors

then 또는 catch로 처리되기 전에 요청과 응답을 가로채서 헤더 설정, 토큰 설정, 에러 스테이터스를 통한 처리 등 중간에 필요한 작업들을 추가해 줄 수 있습니다.

axios에서 제공하는 기본 인터셉터는 다음과 같은 방식으로 쓸 수 있습니다.

// 요청 인터셉터 추가하기
axios.interceptors.request.use(function (config) {
    // 요청이 전달되기 전에 작업 수행
    return config;
  }, function (error) {
    // 요청 오류가 있는 작업 수행
    return Promise.reject(error);
  });

// 응답 인터셉터 추가하기
axios.interceptors.response.use(function (response) {
    // 2xx 범위에 있는 상태 코드는 이 함수를 트리거합니다.
    // 응답 데이터가 있는 작업 수행
    return response;
  }, function (error) {
    // 2xx 외의 범위에 있는 상태 코드는 이 함수를 트리거합니다.
    // 응답 오류가 있는 작업 수행
    return Promise.reject(error);
  });

Axios 더 알아보기

Progress Event 다루기

axios.post('https://api.example.com/upload', formData, {
	// axios는 onDownloadProgress도 지원합니다. 
  onUploadProgress: progressEvent => {
    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`Upload progress: ${percentCompleted}%`);
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

❗️타입스크립트를 사용하는 경우 'progressEvent.total'은(는) 'undefined'일 수 있습니다.’라는 ****에러를 마주할 수 있는데, ??(Nullish coalescing 널 병합 연산자)로 undefined일 경우 기본값(1)을 설정해서 에러를 해결할 수 있습니다.

axios.post('https://api.example.com/upload', formData, {
  onUploadProgress: progressEvent => {
    const percentCompleted = Math.round(
            ((progressEvent?.loaded ?? 0) * 100) / (progressEvent?.total ?? 1)
          );
    console.log(`Upload progress: ${percentCompleted}%`);
  }
})


Reference
https://yamoo9.github.io/axios/guide/api.html#구성-옵션
https://inpa.tistory.com/entry/AXIOS-📚-설치-사용

0개의 댓글