후기/evertrip

<React> customAxios 작성

잼추 2024. 5. 25. 03:21

api 사용시 config filter때문에 계속 authorization error가 나와서
보니 header에 authorization cookie값을 넣어줘야

filter 통과가 된다는 걸 알게되었다.

 

그래서 cookie 에서 값을 들고 온다음 header에 넣어줬더니

드디어 작성한 api를 사용할 수 있었다.

 

이걸 사용할때 마다 cookie에서 값을 가져와서 사용 할 것을 생각하니
무조건 메소드화를 시켜야 겠다고 생각했다.

 

그래서 custumAixos를 작성하게 되었다.

 

import axios, { AxiosResponse } from 'axios';
import { Cookies } from 'react-cookie';

// 정확한 HTTP 메소드 타입을 정의합니다.
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

const CustomAxios = async (method: HttpMethod, url: string, param?: any) => {
  const cookies = new Cookies();

  const getCookie = (name: string) => {
    return cookies.get(name);
  }

  const config = {
    headers: {
      'Authorization': `Bearer ${getCookie('Authorization')}`
    }
  };

  let response: AxiosResponse<any>;

  try {
    switch (method) {
      case 'GET':
        response = await axios.get(url, config);
        break;
      case 'POST':
        response = await axios.post(url, param, config);
        break;
      case 'PUT':
        response = await axios.put(url, param, config);
        break;
      case 'DELETE':
        response = await axios.delete(url, config);
        break;
      default:
        throw new Error('Invalid HTTP method');
    }

    return { code: response.status, data: response.data };
  } catch (error: any) {
    if (axios.isAxiosError(error) && error.response) {
      return { code: error.response.status, data: error.response.data.error };
    } else {
      console.error('An unknown error occurred:', error);
      return { code: null, data: null };
    }
  }
}

export default CustomAxios;

 

사용 예시

import React, { useEffect, useState, useRef } from 'react';
import { Box } from '@mui/material';
import CustomAxios from './CustomAxios'; // 경로를 확인하세요

const Test = () => {
  const [response1, setResponse1] = useState<any>(null);
  const [response2, setResponse2] = useState<any>(null);
  const postExecuted = useRef(false); // useRef로 플래그 설정

  // GET 요청을 통해 response1 데이터를 가져옴
  useEffect(() => {
    const fetchResponse1 = async () => {
      const response1Data = await CustomAxios('GET', 'http://localhost:8080/api/posts/1');
      setResponse1(response1Data.data);
    };

    fetchResponse1();
  }, []);

  // POST 요청을 한 번만 실행
  useEffect(() => {
    const postData = async () => {
      const principalData = await CustomAxios('GET', 'http://localhost:8080/member');
      const data = {
        dto: {
          title: 'new1'
        },
        principal: principalData.data
      };

      const response = await CustomAxios('POST', 'http://localhost:8080/api/posts', data);
      setResponse2(response);
    };

    // POST 요청이 한 번만 실행되도록 설정
    if (!postExecuted.current) {
      postExecuted.current = true;
      postData();
    }
  }, []); // 빈 배열을 의존성 배열로 전달하여 한 번만 실행되도록 설정

  return (
    <Box>
      <Box>{JSON.stringify(response1)}</Box>
      --------
      <Box>{JSON.stringify(response2)}</Box>
    </Box>
  );
};

export default Test;