[API 개선] useApi 함수 리팩토링 및 API 플러그인 추가로 API 호출 방식 통일

This commit is contained in:
2025-08-29 10:32:21 +09:00
parent 41f8ec3232
commit 8af0cf5a44
2 changed files with 79 additions and 35 deletions

44
plugins/api.ts Normal file
View File

@@ -0,0 +1,44 @@
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig();
const baseURL = `${config.public.apiBase}${config.public.contextPath}`;
const api = $fetch.create({
baseURL,
credentials: "include",
onRequest({ request, options }) {
// 1) GET/HEAD가 아니면 body만 넣기 (GET에 body 금지)
const method = (options.method ?? "GET").toUpperCase();
if (method === "GET" || method === "HEAD") {
delete (options as any).body;
}
// 2) FormData면 Content-Type 자동 지정 금지
const isFormData =
typeof FormData !== "undefined" && options.body instanceof FormData;
options.headers = {
...(isFormData ? {} : { "Content-Type": "application/json" }),
...(options.headers || {}),
};
// 3) SSR 쿠키 포워딩
if (import.meta.server) {
const cookie = useRequestHeaders(["cookie"])?.cookie;
// request가 절대 URL이면 호스트 비교
const reqUrl = typeof request === "string" ? request : String(request);
const isBackendApi =
!reqUrl.startsWith("http") || // 상대경로면 내 API
reqUrl.startsWith(baseURL); // 혹은 baseURL과 동일
if (cookie && isBackendApi) {
options.headers = { ...(options.headers || {}), cookie } as any;
}
}
},
onResponseError({ response }) {
// 공통 로깅
console.error("[API ERROR]", response.status, response._data);
},
});
return { provide: { api } };
});