데이터 패칭 라이브러리 - Axios (2. get과 post)

eeensu·2024년 1월 31일
post-thumbnail

GET

Axios의 get 메서드는 HTTP GET 요청을 수행하는 메서드로, 주어진 URL로부터 데이터를 가져온다. 이 메서드는 Promise를 반환하며, 요청이 성공하면 resolve되고, 실패하면 reject된다.

axios.get(url, config)
  .then(response => {
    // 성공적으로 데이터를 가져온 경우의 처리
    console.log(response.data);
  })
  .catch(error => {
    // 요청이 실패한 경우의 처리
    console.error('Error fetching data:', error);
  });

매개변수

  • url
    요청을 보낼 URL

  • config (optional)
    Axios 요청에 대한 구성 옵션을 설정하는 객체이다. get메서드 뿐만 아니라 다른 메서드에서도 사용 가능하며, 이는 HTTP 요청과 관련된 여러 설정을 담고 있다. 많은 옵션들이 있지만, 그중에서 자주 사용하는 것을 간추려 보면 아래와 같다. (data 옵션은 get 메서드에서 사용되지 않음)

    • params
      쿼리 매개변수를 설정하는 객체이다.

      axios.get('/user', {
        params: {
          id: 'my_id',
          name: 'John Doe'
        }
      });

    • headers : HTTP 헤더를 설정하는 객체이다.

      axios.get('/user', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Custom-Header': 'custom-value'
        }
      });

    • timeout : 요청이 얼마 동안 응답을 기다릴지를 밀리초 단위로 설정한다.

      axios.get('/user', {
        timeout: 5000 // 5초
      });

      보다 자세한 옵션은 다음 포스트에서 살펴볼 수 있다.



POST

Axios의 post() 메서드는 HTTP POST 요청을 수행하는 메서드로, 서버로 데이터를 전송할 때 사용된다. 이 메서드도 get() 메서드와 마찬가지로 Promise를 반환하며, 요청이 성공하면 resolve되고, 실패하면 reject된다.

axios.post(url, data, config)

매개변수

  • url
    요청을 보낼 URL 주소

  • data (optional)
    서버로 보낼 데이터를 담은 객체 (주로 POST 요청의 body에 들어감)

  • config (optional)

아래는 post() 메서드의 간단한 사용 예시이다.

import axios from 'axios';

const postData = {
  username: 'john_doe',
  password: 'secret_password'
};

axios.post('https://api.example.com/data', postData)
  .then(response => {
    console.log(response.data); // 응답 데이터
  })
  .catch(error => {
    console.error('Error posting data:', error);
  });
profile
안녕하세요! 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글