[typescript] Axios를 사용하여 RESTful API에 요청 보내는 방법

Axios는 Node.js 및 브라우저를 위한 Promise 기반 HTTP 클라이언트 라이브러리이며, RESTful API와의 통신에 유용하게 사용됩니다. 이 블로그 포스트에서는 TypeScript와 함께 Axios를 사용하여 RESTful API에 요청을 보내는 방법을 살펴보겠습니다.

Axios 설치

먼저, Axios를 설치해야합니다. npm을 사용하여 프로젝트에 Axios를 설치할 수 있습니다.

npm install axios

RESTful API에 GET 요청 보내기

Axios를 사용하여 RESTful API에 GET 요청을 보내는 방법은 간단합니다. 다음은 TypeScript로 작성된 예제 코드입니다.

import axios, { AxiosResponse } from 'axios';

interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

axios.get<Todo[]>('https://jsonplaceholder.typicode.com/todos')
  .then((response: AxiosResponse<Todo[]>) => {
    // 요청 성공 시 처리
    console.log(response.data);
  })
  .catch((error: any) => {
    // 요청 실패 시 처리
    console.error(error);
  });

위의 코드는 Axios를 사용하여 https://jsonplaceholder.typicode.com/todos로 GET 요청을 보내는 예제입니다. 응답은 Todo 배열로 들어올 것으로 기대되며, 성공 또는 실패 시에 대한 적절한 처리를 수행합니다.

RESTful API에 POST 요청 보내기

이제 RESTful API에 POST 요청을 보내는 방법을 살펴보겠습니다. 다음은 TypeScript로 작성된 예제 코드입니다.

interface NewTodo {
  title: string;
  completed: boolean;
}

const newTodo: NewTodo = {
  title: 'New Todo',
  completed: false
};

axios.post<NewTodo>('https://jsonplaceholder.typicode.com/todos', newTodo)
  .then((response: AxiosResponse<NewTodo>) => {
    // 요청 성공 시 처리
    console.log(response.data);
  })
  .catch((error: any) => {
    // 요청 실패 시 처리
    console.error(error);
  });

위의 코드는 Axios를 사용하여 https://jsonplaceholder.typicode.com/todos로 POST 요청을 보내는 예제입니다. 새로운 할 일(New Todo)를 생성하는 요청이며, 성공 또는 실패 시에 대한 적절한 처리를 수행합니다.

마무리

Axios를 사용하면 TypeScript와 함께 간편하게 RESTful API와 통신할 수 있습니다. 이를 통해 개발자는 API 요청 및 응답에 집중할 수 있으며, 코드의 가독성과 유지보수성을 높일 수 있습니다.

이상으로 Axios를 사용하여 RESTful API에 요청을 보내는 방법에 대해 알아보았습니다. 감사합니다.

참고: Axios 공식 문서