feat: 초기 프로젝트 설정 및 룰.md 파일 추가
This commit is contained in:
86
web-ui/js/api-helper.js
Normal file
86
web-ui/js/api-helper.js
Normal file
@@ -0,0 +1,86 @@
|
||||
// /public/js/api-helper.js
|
||||
|
||||
// API 기본 URL 설정
|
||||
const API_BASE = location.hostname.includes('localhost')
|
||||
? 'http://localhost:3005/api'
|
||||
: 'https://api.hyungi.net/api';
|
||||
|
||||
// 인증된 fetch 함수
|
||||
async function authFetch(url, options = {}) {
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
if (!token) {
|
||||
console.error('토큰이 없습니다. 로그인이 필요합니다.');
|
||||
window.location.href = '/index.html';
|
||||
return;
|
||||
}
|
||||
|
||||
const defaultHeaders = {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...defaultHeaders,
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
// 401 에러 시 로그인 페이지로
|
||||
if (response.status === 401) {
|
||||
console.error('인증 실패. 다시 로그인해주세요.');
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = '/index.html';
|
||||
return;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// GET 요청 헬퍼
|
||||
async function apiGet(endpoint) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`);
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// POST 요청 헬퍼
|
||||
async function apiPost(endpoint, data) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// PUT 요청 헬퍼
|
||||
async function apiPut(endpoint, data) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// DELETE 요청 헬퍼
|
||||
async function apiDelete(endpoint) {
|
||||
const response = await authFetch(`${API_BASE}${endpoint}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (!response) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 내보내기 (다른 파일에서 사용 가능)
|
||||
window.API = {
|
||||
get: apiGet,
|
||||
post: apiPost,
|
||||
put: apiPut,
|
||||
delete: apiDelete,
|
||||
fetch: authFetch,
|
||||
BASE: API_BASE
|
||||
};
|
||||
Reference in New Issue
Block a user