init
This commit is contained in:
@@ -16,19 +16,41 @@ export function AuthProvider({ children }) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const login = async (email, password) => {
|
const login = async (email, password) => {
|
||||||
const res = await fetch(`${API_BASE_URL}/auth/login`, {
|
let res;
|
||||||
method: 'POST',
|
try {
|
||||||
headers: { 'Content-Type': 'application/json' },
|
res = await fetch(`${API_BASE_URL}/auth/login`, {
|
||||||
credentials: 'include',
|
method: 'POST',
|
||||||
body: JSON.stringify({ email, password }),
|
headers: { 'Content-Type': 'application/json' },
|
||||||
});
|
credentials: 'include',
|
||||||
if (!res.ok) {
|
body: JSON.stringify({ email, password }),
|
||||||
// 서버가 에러 메시지를 JSON 으로 보낼 수도 있으므로 파싱 시도
|
});
|
||||||
let msg = '로그인 실패';
|
} catch (e) {
|
||||||
try { msg = (await res.json())?.detail || msg; } catch { /* ignore */ }
|
throw new Error('네트워크 오류로 로그인에 실패했습니다. (서버 접속 불가)');
|
||||||
throw new Error(msg);
|
|
||||||
}
|
}
|
||||||
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);
|
setUser(data);
|
||||||
try { localStorage.setItem('auth_user', JSON.stringify(data)); } catch {}
|
try { localStorage.setItem('auth_user', JSON.stringify(data)); } catch {}
|
||||||
return data;
|
return data;
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export default function LoginPage({ onLoggedIn }) {
|
|||||||
await login(email.trim(), password);
|
await login(email.trim(), password);
|
||||||
onLoggedIn?.();
|
onLoggedIn?.();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError('이메일 또는 비밀번호가 올바르지 않습니다.');
|
setError(err?.message || '로그인에 실패했습니다.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user