Computer >> 컴퓨터 >  >> 소프트웨어 >> 브라우저

JavaScript에서 Axios로 HTTP 요청 쉽게 다루기: 기본 사용법 완벽 가이드

JavaScript를 배우고 싶으신가요? jshandbook.com에서 제 전자책을 확인해 보세요.

소개

Axios는 HTTP 요청을 수행하기 위해 널리 사용되는 JavaScript 라이브러리입니다. 브라우저와 Node.js 환경 모두에서 동작하며, IE8을 포함한 모든 최신 브라우저를 지원합니다.

Axios는 프로미스(Promise) 기반으로 설계되어 있어, async/await 문법을 활용하면 XHR 요청을 매우 간결하고 직관적으로 작성할 수 있습니다.

네이티브 Fetch API 대비 Axios가 가지는 장점은 다음과 같습니다.

  • 구형 브라우저 지원 (Fetch는 폴리필(polyfill)이 필요)
  • 요청 취소(abort) 기능 제공
  • 응답 타임아웃 설정 가능
  • CSRF 보호 기능 내장
  • 업로드 진행 상황(upload progress) 지원
  • JSON 데이터 자동 변환
  • Node.js 환경 지원

설치 방법

Axios는 npm으로 설치할 수 있습니다.

npm install axios

yarn을 사용하는 경우:

yarn add axios

또는 unpkg.com을 통해 페이지에 직접 포함시킬 수도 있습니다.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios API 살펴보기

axios 객체에서 바로 HTTP 요청을 시작할 수 있습니다.

axios({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get',
  data: {
    foo: 'bar'
  }
})

하지만 편의상 일반적으로 아래 메서드들을 더 많이 사용합니다.

  • axios.get()
  • axios.post()

(jQuery에서 $.ajax() 대신 $.get(), $.post()를 사용하듯이 말입니다.)

덜 자주 쓰이지만 여전히 유용한 나머지 HTTP 메서드도 모두 지원합니다.

  • axios.delete()
  • axios.put()
  • axios.patch()
  • axios.options()

또한 응답 본문(body)은 버리고 헤더(header)만 가져오는 메서드도 제공합니다.

GET 요청 처리하기

Axios를 활용하는 가장 편리한 방법 중 하나는 최신(ES2017) async/await 문법을 사용하는 것입니다.

다음 Node.js 예제는 axios.get()을 이용해 Dog API에서 전체 견종 목록을 조회하고, 그 개수를 세어 출력합니다.

const axios = require('axios')

const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = await getBreeds()

  if (breeds.data.message) {
    console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
  }
}

countBreeds()

async/await를 사용하지 않으려면 프로미스 문법으로도 작성할 수 있습니다.

const axios = require('axios')

const getBreeds = () => {
  try {
    return axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = getBreeds()
    .then(response => {
      if (response.data.message) {
        console.log(
          `Got ${Object.entries(response.data.message).length} breeds`
        )
      }
    })
    .catch(error => {
      console.log(error)
    })
}

countBreeds()

GET 요청에 파라미터 추가하기

GET 요청은 URL에 파라미터를 담을 수 있습니다. 예를 들어 https://site.com/?foo=bar처럼 말입니다.

Axios에서는 해당 URL을 그대로 사용하면 됩니다.

axios.get('https://site.com/?foo=bar')

또는 옵션 객체에 params 속성을 지정하는 방법도 있습니다.

axios.get('https://site.com/', {
  params: {
    foo: 'bar'
  }
})

POST 요청 처리하기

POST 요청은 GET 요청과 거의 동일하지만, axios.get 대신 axios.post를 사용한다는 점만 다릅니다.

axios.post('https://site.com/')

POST 파라미터를 담은 객체는 두 번째 인자로 전달합니다.

axios.post('https://site.com/', { foo: 'bar' })
JavaScript를 배우고 싶으신가요? jshandbook.com에서 제 전자책을 확인해 보세요.