2023년 6월 26일 월요일

Axios 라이브러리를 이용한 REST API 호출

 Axios는 JavaScript에서 사용할 수 있는 강력한 HTTP 클라이언트 라이브러리입니다. 이 라이브러리를 사용하면 REST API 호출을 간편하게 처리할 수 있습니다. 아래는 Axios를 사용하여 REST API를 호출하는 방법에 대한 자세한 설명입니다.


1. Axios 설치하기

먼저, 프로젝트에 Axios를 설치해야 합니다. npm을 사용하는 경우, 다음 명령어를 사용하여 Axios를 설치할 수 있습니다:

npm install axios

또는 yarn을 사용하는 경우, 다음 명령어를 사용하세요:

yarn add axios


2. Axios 라이브러리 가져오기


Axios를 사용하기 위해 해당 라이브러리를 import 또는 require하여 가져와야 합니다. 일반적으로 다음과 같은 방법으로 가져올 수 있습니다:

import axios from 'axios';
// 또는
const axios = require('axios');


3. REST API 호출


Axios를 사용하여 REST API를 호출하려면 axios 객체의 메서드를 사용해야 합니다. axios 객체에는 다양한 메서드가 있으며, 그 중에서도 가장 일반적으로 사용되는 메서드는 get, post, put, delete입니다.
GET 요청:
GET 요청은 서버로부터 데이터를 가져오는데 사용됩니다. 다음은 GET 요청을 보내는 예시입니다:

axios.get('https://api.example.com/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

POST 요청:
POST 요청은 서버로 데이터를 전송하고 새로운 리소스를 생성하는 데 사용됩니다. 다음은 POST 요청을 보내는 예시입니다:

axios.post('https://api.example.com/users', {
    name: 'John Doe',
    email: 'john@example.com'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });


PUT 요청:
PUT 요청은 서버에 데이터를 업데이트하는 데 사용됩니다. 다음은 PUT 요청을 보내는 예시입니다:

axios.put('https://api.example.com/users/1', {
    name: 'Updated Name',
    email: 'updated@example.com'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });


DELETE 요청:
DELETE 요청은 서버에서 리소스를 삭제하는 데 사용됩니다. 다음은 DELETE 요청을 보내는 예시입니다:

axios.delete('https://api.example.com/users/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });


추가 설정:
Axios는 기본적으로 많은 기능을 제공합니다. 그러나 필요에 따라 요청에 대한 추가 설정을 할 수도 있습니다. 예를 들어, 헤더를 설정하거나 요청 시간 초과를 지정하는 등의 작업이 가능합니다.
헤더 설정:

axios.get('https://api.example.com/users', {
    headers: {
      'Authorization': 'Bearer token'
    }
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });


요청 시간 초과 설정:

axios.get('https://api.example.com/users', {
    timeout: 5000 // 5초
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });


위의 내용을 참고하여 Axios를 사용하여 REST API 호출을 수행할 수 있습니다. Axios는 다양한 기능과 설정을 제공하기 때문에, 문서를 참조하면 더 많은 옵션을 알아볼 수 있습니다.

댓글 없음:

댓글 쓰기