-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaxiosInstance.ts
More file actions
84 lines (67 loc) · 2.03 KB
/
axiosInstance.ts
File metadata and controls
84 lines (67 loc) · 2.03 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import axios from 'axios';
// Axios 인스턴스
const apiRequest = axios.create({
baseURL: import.meta.env.VITE_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
// 요청 인터셉터
apiRequest.interceptors.request.use(async (config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// 응답 인터셉터
apiRequest.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
const noAuthNeeded = [
'/api/v1/auth/token',
'/api/v3/auth/signup',
'/api/v3/auth/google',
'/api/v3/auth/reissue',
];
const isNoAuth = noAuthNeeded.some((url) =>
originalRequest.url?.includes(url)
);
const isLoginPage = window.location.pathname.startsWith('/login');
if (
error.response &&
(error.response.status === 401 || error.response.status === 403) &&
!originalRequest._retry &&
!isNoAuth &&
!isLoginPage
) {
originalRequest._retry = true;
try {
const res = await axios.post(
`${import.meta.env.VITE_BASE_URL}/api/v3/auth/reissue`,
{},
{
withCredentials: true,
}
);
const newAccessToken = res.data.data.token;
localStorage.setItem('token', newAccessToken);
window.postMessage(
{ type: 'SET_TOKEN', token: newAccessToken },
window.location.origin
);
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return apiRequest(originalRequest);
} catch (reissueError) {
console.error('토큰 재발급 실패. 다시 로그인해주세요.', reissueError);
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
window.location.href = '/onboarding?step=SOCIAL_LOGIN';
return Promise.reject(reissueError);
}
}
return Promise.reject(error);
}
);
export default apiRequest;