React

[React] 리액트 Axios 사용법

이경욱 2023. 11. 21. 20:24

axios란?

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

프론트 & 백엔드 간의 원활한 통신을 위해 사용

자바스크립트에는 fetch API가 있지만, 프레임워크에서 ajax를 구현할 땐 axios를 쓰는 편이다.

 

 

 

 

특징

운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는

Node.js의 http api 사용

Promise API 사용

요청과 응답 데이터의 변형

HTTP 요청 취소

HTTP 요청과 응답을 JSON 형태로 자동 변경

 

 

 

 

axios 와 fetch의 차이점

구분 axios fetch
1 써드파티 라이브러리  내부 API
2 XSRF 보호 X
3 data 속성을 사용 body 속성을 사용
4 object 포함 문자열 변환
5 JSON 자동 변환 .json() 메서드 사용
6 취소 및 타임아웃 기능 X

 

 

 

 

Axios CDN 

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

 

 

 

 

Axios 다운로드

// 사용하는 패키지 매니저로 설치
yarn add axios
npm install axios

 

 

 

 

Axios 파라미터 옵션

  • method : 요청방식 (default get)
  • url : 서버주소
  • baseURL : 상대경로를 사용할 때 고정되는 url 주소
  • headers : 요청 헤더
  • data : method가 'PUT' ,'POST', 'PATCH' 일 경우 body에 보내는 데이터
  • params : URL 파라미터
  • timeout : 지정 시간 초과 시 요청 취소
  • responseType : 서버가 응답해주는 데이터의 타입 지정
  • transformRequest : 서버에 전달되기 전에 요청 데이터를 변경
    •  method가 'PUT, POST, PATCH, DELETE' 에 해당하는 경우만 가능
    •  배열의 마지막 함수는 string, Buffer, ArrayBuffer 중 하나로 반환
    •  header 객체를 수정 가능
  • transformResponse : 응답 데이터가 만들어지기 전에 변환 가능
  • withCredentials : cross-site-access-control 요청 허용 여부 (true 시 cross-origin 쿠키값 전달)
  • maxContentLength : http 응답 내용의 max 사이즈를 지정
  • validateStatus : HTTP 응답 상태 코드에 따라 promise 반환 값을 resolve / reject 지정
  • maxRedirects : node.js 에서 사용되는 리다이렉트 최대치 지정
  • proxy : proxy 서버의 hostname과 port를 정의하는 옵션
  • cancelToken : 요청 최소 시 사용되는 토큰 명시

 

 

 

 

 

HTTP Methods

 

1. GET : 입력한 url에 존재하는 자원을 요청합니다.

axios.get("url"[,config]);

 

const axios = require('axios');

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });
 

// 옵션
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });  
 
 
// async/await
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

 

 

 

2. POST : 새로운 리소스를 생성할 때 사용합니다.

데이터를 Message Body에 포함시켜서 전송합니다.

ex) 로그인, 회원가입 등 사용자가 생성한 파일을 서버에 업로드할 때 사용.

axios.post("url",{data},[,config])

 

axios.post("url", {
		firstData: 'first',
		secondData: 'second'
    })
    .then(function (response) {
    	console.log(response)
    }).catch(function (error) {
        console.log(error)
    })

 

 

 

3. DELETE : 데이터베이스에 저장되어 있는 내용을 삭제

axios.delete("url"[,config]);

 

axios.delete('/user?ID=12345',{
// query가 길어질 경우 data 객체 추가 가능
    data: {
      post_id: 1,
      comment_id: 13,
      username: "foo"
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })

 

 

 

4. PUT : 데이터베이스에 저장되어 있는 내용을 갱신

axios.put("url",{data},[,config])

 

axios.put("url", {
        username: "",
        password: ""
    })
    .then(function (response) {
    	console.log(response)
    }).catch(function (error) {
    	console.log(error)
    })

 

 

 

5. 멀티 요청 : 여러 개의 요청을 동시에 수행할 경우

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));