[React] react-axios

I'm Your Cho-i·2022년 9월 14일
1

React

목록 보기
6/13
post-thumbnail

📌 Axios란 ?

  • Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
  • 쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용
  • 이미 자바스크립트에는 fetch api가 있지만, 프레임워크에서 ajax를 구현할땐 axios를 쓰는 편

비동기 방식

  • 비동기 방식은 웹페이지를 리로드 하지 않아도 데이터를 불러와주는 방식
  • 결과가 주어지는데 시간이 걸리지만 그 시간 동안에는 다른작업을 병행할 수 있다는 장점과 자원을 효율적으로 사용

📌 Axios 특징

  • 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용
  • Promise(ES6) API 사용
  • 요청과 응답 데이터의 변형
  • HTTP 요청 취소
  • HTTP 요청과 응답을 JSON 형태로 자동 변경

📌 Axios 사용

👉 설치

npm install axios

👉 추가

import axios from "axios";

👉 메소드

axios의 대표적 Request method
GET : axios.get(url[, config])
POST : axios.post(url, data[, config])
PUT : axios.put(url, data[, config])
DELETE : axios.delete(url[, config])

기타

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]])

◻ GET

입력한 url이 존재하는 자원에 요청을 보냄

axios.get(url,[,config])

GET방식은 서버에서 어떤 데이터를 가져와서 보여줄것인가를 정하는 용도.
주소에 있는 쿼리스트링을 활용해 정보를 전달하는 것이고 GET 메서드는 값이나 상태등을 직접 바꿀수 없음.

// user에게 할당된 id 값과 함께 요청을 합니다.
axios.get('/user?ID=12345')
  .then(function (response) {
    // 성공했을 때
    console.log(response);
  })
  .catch(function (error) {
    // 에러가 났을 때
    console.log(error);
  })
  .finally(function () {
    // 항상 실행되는 함수
  });

// 위와는 같지만, 옵션을 주고자 할 때는 이렇게 요청을 합니다.
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 함수/메소드를 만듭니다. 
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

◻ POST

새로운 리소스를 생성(create)할 때 사용

axios.post("url주소",{ data객체 },[,config])

POST 메서드의 두 번째 인자는 본문으로 보낼 데이터를 설정한 객체 리터럴을 전달

axios.post("url", {
		firstName: 'Lee',
		lastName: 'choI'
    })
    .then(function (response) {
        // response  
    }).catch(function (error) {
        // 오류발생시 실행
    })

◻ PUT

데이터베이스에 저장된 내용을 갱신(수정)하는 목적으로 사용

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

axios.put("url", {
        username: "",
        password: ""
    })
    .then(function (response) {
         // response  
    }).catch(function (error) {
        // 오류발생시 실행
    })

서버 내부적으로 get -> post 과정을 거치기 때문에 post 메서드와 비슷한 형태

◻ DELETE

데이터베이스에 저장된 내용을 삭제하는 목적으로 사용

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

axios.delete('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })

📌 Axios custom hooks

https://levelup.gitconnected.com/react-custom-hook-useaxios-689fe5a12045


참고 : https://axios-http.com/kr/docs/example

profile
https://github.com/Cho-i

0개의 댓글