📌 API 통신 방법 정리 (컴공 회의실)

2025. 3. 1. 15:25프론트엔드/Next JS

728x90

📌 API 통신 방법 정리

API 통신을 설정하는 과정에서 여러 가지 문제가 발생했지만, 이를 해결하는 과정에서 중요한 개념들을 정리할 수 있었습니다.
이번 글에서는 API 통신 방법과 관련된 핵심 개념을 정리하고, 실제 개발 중 발생한 문제와 해결 방법을 공유하겠습니다.


🚀 1. API 통신 방식

API(Application Programming Interface)는 클라이언트와 서버 간의 데이터 송수신을 위한 인터페이스입니다.
대표적인 통신 방식은 다음과 같습니다.

📌 (1) REST API

REST(Representational State Transfer) 방식은 HTTP 프로토콜을 기반으로 클라이언트와 서버가 데이터를 주고받는 방식입니다.

  • 특징
    • HTTP 메서드(GET, POST, PUT, DELETE)를 사용
    • URL을 리소스 중심으로 설계 (/api/users, /api/products/1)
    • Stateless(무상태성): 요청 간 상태 정보를 저장하지 않음
  • 요청 예제 (Axios)
  • axios.get('https://csiereserve.store/api/notice') .then(response => console.log(response.data)) .catch(error => console.error(error));

📌 (2) 인증 방식

API 요청에서 보안을 위해 인증(Authentication)과 권한(Authorization) 체크가 필요합니다.

🔹 1) Bearer Token (JWT)

Bearer Token은 OAuth 2.0과 함께 사용되는 방식으로, JWT(JSON Web Token)를 Authorization 헤더에 포함하여 인증을 수행합니다.

  • 요청 헤더 형식
  • Authorization: Bearer {accessToken}
  • 요청 예제 (Axios)
  • axios.get('https://csiereserve.store/api/notice', { headers: { 'Authorization': `Bearer ${localStorage.getItem('accessToken')}` } })
  • 문제 해결
    • Bearer 없이 토큰을 보내면 서버가 이를 인식하지 못할 수 있음
    • Authorization 헤더가 노출되지 않는 경우 CORS 설정에서 exposedHeaders를 추가해야 함

🔹 2) 쿠키 기반 인증

쿠키를 활용하여 로그인 후 서버가 인증 정보를 유지하는 방식입니다.

  • 요청 예제 (withCredentials 설정 필수)
    axios.post('https://csiereserve.store/api/login', payload, {
      withCredentials: true
    });
    
  • 장점
    • 자동으로 쿠키가 포함되므로 Authorization 헤더를 따로 설정할 필요 없음
  • 단점
    • CORS 설정이 필요 (credentials: true 설정)

2. 통신 중 발생한 문제 및 해결 방법

🔹 1) 403 Forbidden 오류

📌 문제:
서버에서 API 요청이 거부됨 (403 Forbidden)

📌 원인 및 해결 방법:

  1. Authorization 헤더에 Bearer을 포함하지 않음 → 토큰 앞에 Bearer 추가
  2. withCredentials: true 설정 없이 쿠키 요청을 보냄 → withCredentials: true 추가
  3. 백엔드 CORS 정책이 잘못 설정됨 → CORS 설정에서 allowedHeaders 및 exposedHeaders 수정
    configuration.setExposedHeaders(Arrays.asList("Authorization"));
    

🔹 2) 400 Bad Request 오류

📌 문제:
API 요청이 올바르지 않다는 400 Bad Request 오류 발생

📌 원인 및 해결 방법:

  1. 요청 형식이 맞지 않음
    • API 문서를 확인하여 요청 형식을 검토 (필요한 파라미터 누락 확인)
    curl -X GET https://csiereserve.store/api/faq/getAll -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
    
  2. 서버에서 예상하는 헤더가 누락됨
    • Content-Type: application/json이 필요한 경우 헤더에 추가
    headers: { 'Content-Type': 'application/json' }
    

🔹 3) CORS 문제로 인해 Authorization 헤더가 보이지 않는 경우

📌 문제:
클라이언트에서 response.headers['authorization']이 undefined로 나옴.

📌 해결 방법:
백엔드에서 CORS 설정을 올바르게 구성해야 함.

Spring Boot CORS 설정

configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.setAllowCredentials(true);

Node.js (Express) CORS 설정

app.use(cors({
  origin: 'https://csiereserve.store',
  credentials: true,
  allowedHeaders: ['Authorization', 'Content-Type'],
  exposedHeaders: ['Authorization']
}));

🔹 4) Git 관련 오류

📌 문제:
Git에서 fatal: no email was given and auto-detection is disabled 오류 발생.

📌 해결 방법:
Git 사용자 정보를 설정해야 함.

git config --global user.name "Your Name"
git config --global user.email "your-email@example.com"

🚀 3. 최종 정리

발생 문제 해결 방법

403 Forbidden Authorization 헤더 확인 (Bearer 포함), withCredentials: true 추가
400 Bad Request API 문서 확인, Content-Type: application/json 추가
CORS 오류로 Authorization 헤더 누락 exposedHeaders: ['Authorization'] 추가
Git 사용자 정보 오류 git config --global user.name 및 user.email 설정

이제 API 통신과 관련된 다양한 문제를 이해하고 해결할 수 있습니다!
🚀 이제 API 통신을 좀 더 원활하게 설정할 수 있겠죠? 😊

728x90