Skip to content

Commit 8e087b4

Browse files
committed
chore:http-client.ts axios interceptors 관련 설정
1 parent 1da07da commit 8e087b4

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/shared/types/api/apiResponse.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,7 @@ export interface ApiResponse<T> {
33
message: string;
44
data?: T;
55
}
6+
7+
export interface ApiErrorResponse {
8+
message?: string;
9+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import axios, { AxiosError, AxiosResponse } from 'axios';
2+
import { ENV } from '../../../config/env.config';
3+
import { ApiErrorResponse } from './apiResponse';
4+
5+
export const axiosClient = axios.create({
6+
baseURL: `${import.meta.env.VITE_REACT_APP_BASE_URL}`,
7+
timeout: 3000,
8+
headers: {
9+
'Content-Type': 'application/json',
10+
},
11+
});
12+
13+
axiosClient.interceptors.request.use(
14+
config => {
15+
const token = localStorage.getItem('access_token');
16+
//zustand 사용함으로써 코드변경 할 듯 현재는 임시 입니다.
17+
18+
if (token) {
19+
config.headers.Authorization = `Bearer ${token}`;
20+
}
21+
22+
if (ENV.IS_DEV) {
23+
console.log('[Request Config]:', config);
24+
}
25+
26+
return config;
27+
},
28+
(error: AxiosError) => {
29+
if (ENV.IS_DEV) {
30+
console.error(`[Request Error]:`, error);
31+
}
32+
return Promise.reject(error);
33+
}
34+
);
35+
36+
axiosClient.interceptors.response.use(
37+
(response: AxiosResponse) => {
38+
if (ENV.IS_DEV) {
39+
console.log('[Response Data]:', response.data);
40+
}
41+
return response;
42+
},
43+
(error: AxiosError<ApiErrorResponse>) => {
44+
const errorInfo = {
45+
status: error.response?.status || 'NETWORK_ERROR',
46+
message: error.response?.data?.message || error.message,
47+
};
48+
49+
if (ENV.IS_DEV) {
50+
console.error(`[API Error - ${error.config?.url}]:`, errorInfo);
51+
}
52+
53+
// 401(토큰 만료)일 경우 로그아웃 처리 or 토큰 갱신 가능
54+
if (errorInfo.status === 401) {
55+
localStorage.removeItem('access_token');
56+
window.location.href = '/login'; // 로그인 페이지로 이동
57+
}
58+
59+
return Promise.reject(errorInfo);
60+
}
61+
);

0 commit comments

Comments
 (0)