From 78a89c000c7c7de0ec6efd0731ac60be14c5f3af Mon Sep 17 00:00:00 2001 From: dsyoon Date: Sat, 27 Dec 2025 15:08:10 +0900 Subject: [PATCH] init --- src/context/AuthContext.jsx | 46 +++++++++++++++++++++++++++---------- src/pages/LoginPage.jsx | 2 +- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/src/context/AuthContext.jsx b/src/context/AuthContext.jsx index c42c2e0..0452a85 100644 --- a/src/context/AuthContext.jsx +++ b/src/context/AuthContext.jsx @@ -16,19 +16,41 @@ export function AuthProvider({ children }) { }, []); const login = async (email, password) => { - const res = await fetch(`${API_BASE_URL}/auth/login`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - credentials: 'include', - body: JSON.stringify({ email, password }), - }); - if (!res.ok) { - // 서버가 에러 메시지를 JSON 으로 보낼 수도 있으므로 파싱 시도 - let msg = '로그인 실패'; - try { msg = (await res.json())?.detail || msg; } catch { /* ignore */ } - throw new Error(msg); + let res; + try { + res = await fetch(`${API_BASE_URL}/auth/login`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ email, password }), + }); + } catch (e) { + throw new Error('네트워크 오류로 로그인에 실패했습니다. (서버 접속 불가)'); } - const data = await res.json(); // { user_id, email } + + // 성공/실패 모두에서 가능한 한 상세 메시지 추출 + const contentType = res.headers.get('content-type') || ''; + const readBody = async () => { + if (contentType.includes('application/json')) { + try { return await res.json(); } catch { return null; } + } + try { return await res.text(); } catch { return null; } + }; + const body = await readBody(); + + if (!res.ok) { + const detail = + (body && typeof body === 'object' && (body.detail || body.message)) || + (typeof body === 'string' ? body.slice(0, 200) : null); + throw new Error(detail ? `${detail} (HTTP ${res.status})` : `로그인 실패 (HTTP ${res.status})`); + } + + if (!body || typeof body !== 'object') { + // 프록시/라우팅 문제로 HTML이 내려오는 경우를 빠르게 식별 + throw new Error(`로그인 응답이 JSON이 아닙니다. Apache 프록시(/auth) 설정을 확인하세요. (HTTP ${res.status})`); + } + + const data = body; // { user_id, email } setUser(data); try { localStorage.setItem('auth_user', JSON.stringify(data)); } catch {} return data; diff --git a/src/pages/LoginPage.jsx b/src/pages/LoginPage.jsx index da09ebf..e3315d7 100644 --- a/src/pages/LoginPage.jsx +++ b/src/pages/LoginPage.jsx @@ -14,7 +14,7 @@ export default function LoginPage({ onLoggedIn }) { await login(email.trim(), password); onLoggedIn?.(); } catch (err) { - setError('이메일 또는 비밀번호가 올바르지 않습니다.'); + setError(err?.message || '로그인에 실패했습니다.'); } };