CORS 문제 해결 트러블슈팅

1. 초기 문제 상황


// 초기 문제가 된 코드
const handleLogin = async (e: React.FormEvent) => {
  try {
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_DNS}/api/user-service/login`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      }
    );
// ...
  } catch (error) {
// ...
  }
};

2. 해결 방법

2.1 API Route 구현


// app/api/login/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { API_URL_CONFIG, API_BASE_URL } from '@/config/apiEndPointConfig';
import axiosInstance from '@/lib/axios';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const response = await axiosInstance.post(
      `${API_BASE_URL.DNS}${API_URL_CONFIG.AUTH.LOGIN}`,
      body,
      {
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );

    return NextResponse.json(response.data);
  } catch (error) {
    console.error('Login error:', error);
    return NextResponse.json(
      { error: '로그인에 실패했습니다.' },
      { status: 401 }
    );
  }
}

2.2 클라이언트 코드 수정


// login/page.tsx
const handleLogin = async (e: React.FormEvent) => {
  try {
    const response = await axiosInstance.post('/api/login', {
      email,
      password
    });

    const nickname = response.data;
// ...처리 로직
  } catch (error) {
// ...에러 처리
  }
};

3. 해결 원리

  1. 클라이언트에서 직접 백엔드로 요청하지 않고 Next.js API Route를 통해 요청
  2. API Route는 서버 사이드에서 실행되므로 CORS 제한을 받지 않음
  3. 백엔드 서버와의 통신은 서버 사이드에서 처리

4. 장점

  1. CORS 문제 해결
  2. 클라이언트의 API 요청 로직 단순화
  3. 환경 변수와 민감한 정보를 클라이언트에 노출하지 않음