fix: API 조회 시 빈 데이터일 경우 에러 처리
This commit is contained in:
@@ -5,11 +5,29 @@ const BASE_URL = process.env.NEXT_PUBLIC_SEWERAGE_API_URL || '';
|
||||
export const getData = async (url: string, data?: object): Promise<any> => {
|
||||
const res = await fetch(url.startsWith('/') ? `${url}` : `${BASE_URL}/${url}`, {
|
||||
method: "GET",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
return data;
|
||||
try {
|
||||
// 응답이 비어있는지 확인
|
||||
const contentLength = res.headers.get('content-length');
|
||||
if (contentLength === '0') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 응답 텍스트를 먼저 가져와서 빈 문자열인지 확인
|
||||
const text = await res.text();
|
||||
if (!text || text.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// JSON 파싱 시도
|
||||
const data = JSON.parse(text);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('JSON parsing error:', error);
|
||||
// JSON 파싱에 실패한 경우, 원본 텍스트 또는 null 반환
|
||||
throw new Error('Invalid JSON response from server');
|
||||
}
|
||||
}
|
||||
throw new Error('Failed to fetch data');
|
||||
};
|
||||
@@ -93,7 +111,7 @@ export const getCmsData = async (url: string, data?: object): Promise<any> => {
|
||||
throw new Error('Failed to fetch data');
|
||||
};
|
||||
|
||||
export function getCookie(name:string) {
|
||||
export function getCookie(name: string) {
|
||||
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
|
||||
if (match && match[2]) {
|
||||
return decodeURIComponent(match[2]);
|
||||
|
||||
Reference in New Issue
Block a user