본문 바로가기
React

[React] Axios 사용법 정리

by inwoo1324 2022. 8. 21.

Axios란?

Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리입니다.

 

지원브라우저

 

Axios와 Fetch의 차이점 

X Axios Fetch
1 요청 객체에 url을 가지고 있다 요청 객체에 url이 없다
2 설치과정이 필요하다 대부분의 최신 브라우저에 내장되어 있어 설치가 필요없다
3 내장된 XSRF 보호기능이 있다 기능 없음
4 data 속성을 사용한다. body 속성을 사용한다.
5 data에는 객체가 포함되어 있다 body는 문자열화 되어야 한다.
6 status가 200 이고 statusText가 'OK' 일 때 요청은 정상이다 응답 객체에 OK 속성이 포함되어 있으면 요청은 정상이다
7 JSON 데이터의 자동 변환 수행한다. json()메서드를 사용해야 한다.
8 요청 취소 및 타임아웃 기능이 존재 기능 없음
9 HTTP 요청을 가로챌 수 있는 기능이 있다 기능 없음
10 다운로드 진행률에 대한 지원이 내장되어 있다. 기능 없음
11 더 많은 브라우저를 지원한다. Chrome 42 이상, Firefox 39 이상, Edge 14 이상, Safari 10.1 이상만 ㅇ지원한다.

fetch와 axios 는 유사하다고 생각할 수 있지만 위 표를 보았을 때 Axios는 별도 설치가 필요한 단점 외에는

Fetch보다 기능적으로나 지원같은 것들이 더 많습니다.

그래서 Fecth는 간단한 경우에 사용하고 그 외에는 Axios를 사용하는 것이 좋을 것 같습니다.

 

Axios 다운로드

npm 사용하기

npm i axios

bower 사용하기

bower install axios

yarn 사용하기

yarn add axios

jsDelivr CDN 사용하기 (html에서 사용)

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

unpkg CDN 사용하기 (html에서 사용)

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

 

자주 사용하는 Axios 단축 메소드

URL이라는 변수에 우리가 원하는 주소를 담습니다.

GET 사용

import axios from 'axios';

axios.get(URL).then((response)=>{
    console.log(response.data);    // 성공
}).catch((error)=>{
    console.log(error);       // 실패
})

비동기 통신 요청

import axios from 'axios';

async function get() {
  try {
    const response = await axios.get(URL);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

동시 요청

function getUserAccount() {
  return axios.get(URL1);
}

function getUserPermissions() {
  return axios.get(URL2);
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });

 POST 사용

import axios from 'axios';

axios.post(URL, {
    id: 'abc1',
    pw: 1234
  })
  .then(function (response) {
    console.log(response);        //성공
  })
  .catch(function (error) {
    console.log(error);           //실패
  });

Delete 사용

axios.delete(URL)
  .then(function (response) {
    console.log(response);        // 성공
  })
  .catch(function (error) {
    console.log(error);           // 실패
  })

query나 params가 많아져서 헤더에 많은 정보를 담을 수 없을 때는 아래와 같이 두번 째 인자에 data를 추가해줄 수 있다.

axios.delete(URL,{
    data: {
      post_id: 1,
      comment_id: 13,
      username: "foo"
    }
  })
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })

 PUT 사용

axios.PUT(URL, {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);        //성공
  })
  .catch(function (error) {
    console.log(error);           //실패
  });

 

Axios 요청 메소드 명령어

편의를 위해 지원하는 모든 요청 메소드의 명령어를 제공합니다.

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

 

 

 

참고 사이트

https://www.geeksforgeeks.org/difference-between-fetch-and-axios-js-for-making-http-requests/

 

Difference between Fetch and Axios.js for making http requests - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

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

 

시작하기 | Axios Docs

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

axios-http.com

'React' 카테고리의 다른 글

[React] Lists and Key  (0) 2022.08.12
[React] useState 사용법 정리  (0) 2022.08.06