[typescript] 타입스크립트에서 Axios를 이용하여 GraphQL 요청 보내는 방법

타입스크립트에서 Axios를 사용하여 GraphQL 요청을 보내는 방법을 소개합니다.

Axios 설치

먼저, Axios를 설치해야 합니다. 아래의 명령을 사용하여 Axios를 프로젝트에 추가합니다.

npm install axios

또는

yarn add axios

GraphQL 요청 보내기

GraphQL 요청을 보내기 위해 Axios를 사용할 때는 POST 요청을 사용해야 합니다. 또한, 요청 헤더에 Content-Type: application/json을 추가해야 합니다.

아래는 TypeScript에서 Axios를 사용하여 GraphQL 요청을 보내는 예제 코드입니다.

import axios, { AxiosResponse } from 'axios';

interface GraphQLResponse {
  data: any;
  errors?: any[];
}

const sendGraphQLRequest = async (query: string, variables?: any): Promise<GraphQLResponse> => {
  const url = 'https://your-graphql-endpoint.com'; // GraphQL 엔드포인트 URL을 입력하세요
  const headers = {
    'Content-Type': 'application/json',
  };

  try {
    const response: AxiosResponse<GraphQLResponse> = await axios.post(url, {
      query,
      variables,
    }, {
      headers,
    });

    return response.data;
  } catch (error) {
    return { data: null, errors: [error.message] };
  }
};

// GraphQL 요청 보내기
const query = `{
  users {
    id
    name
  }
}`;

sendGraphQLRequest(query)
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

위 코드에서 sendGraphQLRequest 함수는 GraphQL 쿼리와 옵셔널한 변수를 받아서 Axios를 사용하여 GraphQL 요청을 보냅니다. 요청이 성공하면 응답 데이터가 반환되고, 실패하면 에러가 반환됩니다.

이와 같이 타입스크립트에서 Axios를 사용하여 GraphQL 요청을 보낼 수 있습니다.

더 자세한 정보는 Axios 공식 문서를 참고하세요.