-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathaxiosInstance.ts
More file actions
55 lines (46 loc) · 1.45 KB
/
axiosInstance.ts
File metadata and controls
55 lines (46 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import axios from 'axios';
import { HTTP_STATUS } from '@/api/constant/httpStatus';
import { postRefreshToken } from '@/api/auth/refreshToken';
const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error),
);
// 응답 인터셉터
axiosInstance.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response) {
const { status } = error.response;
if (status === HTTP_STATUS.UNAUTHORIZED) {
try {
const { accessToken } = await postRefreshToken();
localStorage.setItem('accessToken', accessToken);
axiosInstance.defaults.headers.Authorization = `Bearer ${accessToken}`;
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
} catch (refreshError) {
console.error('리프레시 토큰 만료, 재로그인 필요');
return Promise.reject(refreshError);
}
}
if (status === HTTP_STATUS.INTERNAL_SERVER_ERROR) {
// 서버 오류 처리
}
}
return Promise.reject(error);
},
);
export default axiosInstance;