Skip to content

Commit 519ecdb

Browse files
authored
Merge pull request #127 from billilge/fix/#126-token-redirect
[Fix/#126] 토큰 만료 시 리다이렉트 기능 추가
2 parents 58ef693 + 24b35ea commit 519ecdb

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

src/apis/item.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { WelfareItemData } from '@/types/welfareItemType';
22
import PrivateAxiosInstance from '@/services/privateAxiosInstance';
3+
import { isAxiosError } from 'axios';
34

45
// 대여 가능한 복지물품 리스트 불러오기
56
// eslint-disable-next-line import/prefer-default-export
@@ -13,6 +14,9 @@ export const getWelfareItems = async (
1314

1415
return response.data;
1516
} catch (error) {
17+
if (isAxiosError(error)) {
18+
console.log(error);
19+
}
1620
throw new Error(`welfare 목록 불러오기에 실패했습니다: ${error}`);
1721
}
1822
};

src/services/privateAxiosInstance.ts

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,38 +14,50 @@ const getAccessToken = (): string | null => {
1414
return '';
1515
};
1616

17+
const redirectToLogin = () => {
18+
const { pathname } = window.location;
19+
const redirectPages = ['/desktop/login', '/mobile/sign-in'];
20+
21+
if (!redirectPages.includes(pathname)) {
22+
window.location.replace(
23+
pathname.startsWith('/desktop') ? '/desktop/login' : '/mobile/sign-in',
24+
);
25+
}
26+
};
27+
1728
const PrivateAxiosInstance = axios.create({
1829
baseURL: process.env.NEXT_PUBLIC_API_BASE_URI,
1930
headers: {
2031
'Content-Type': 'application/json',
2132
},
2233
});
2334

35+
// 요청 인터셉터
2436
PrivateAxiosInstance.interceptors.request.use(
2537
(config: InternalAxiosRequestConfig) => {
2638
const token = getAccessToken();
27-
if (!token) {
28-
const redirectPages = ['/desktop/login', '/mobile/sign-in'];
29-
const { pathname } = window.location;
30-
31-
if (!redirectPages.includes(pathname)) {
32-
window.location.replace(
33-
pathname.startsWith('/desktop')
34-
? '/desktop/login'
35-
: '/mobile/sign-in',
36-
);
37-
}
3839

40+
if (!token) {
41+
redirectToLogin();
3942
return Promise.reject(new AxiosError('No authentication token found'));
4043
}
4144

4245
const newConfig = { ...config, withCredentials: false };
43-
if (token) {
44-
newConfig.headers.set('Authorization', `Bearer ${token}`);
45-
}
46+
newConfig.headers.set('Authorization', `Bearer ${token}`);
4647
return newConfig;
4748
},
4849
(error) => Promise.reject(error),
4950
);
5051

52+
PrivateAxiosInstance.interceptors.response.use(
53+
(response) => response,
54+
(error: AxiosError) => {
55+
if (error.response?.status === 401) {
56+
localStorage.clear();
57+
redirectToLogin();
58+
}
59+
return Promise.reject(error);
60+
},
61+
);
62+
5163
export default PrivateAxiosInstance;

0 commit comments

Comments
 (0)