diff --git a/src/apis/item.ts b/src/apis/item.ts index 7d27dd7..02d3dd2 100644 --- a/src/apis/item.ts +++ b/src/apis/item.ts @@ -1,5 +1,6 @@ import { WelfareItemData } from '@/types/welfareItemType'; import PrivateAxiosInstance from '@/services/privateAxiosInstance'; +import { isAxiosError } from 'axios'; // 대여 가능한 복지물품 리스트 불러오기 // eslint-disable-next-line import/prefer-default-export @@ -13,6 +14,9 @@ export const getWelfareItems = async ( return response.data; } catch (error) { + if (isAxiosError(error)) { + console.log(error); + } throw new Error(`welfare 목록 불러오기에 실패했습니다: ${error}`); } }; diff --git a/src/services/privateAxiosInstance.ts b/src/services/privateAxiosInstance.ts index 5fd8f20..3849380 100644 --- a/src/services/privateAxiosInstance.ts +++ b/src/services/privateAxiosInstance.ts @@ -14,6 +14,17 @@ const getAccessToken = (): string | null => { return ''; }; +const redirectToLogin = () => { + const { pathname } = window.location; + const redirectPages = ['/desktop/login', '/mobile/sign-in']; + + if (!redirectPages.includes(pathname)) { + window.location.replace( + pathname.startsWith('/desktop') ? '/desktop/login' : '/mobile/sign-in', + ); + } +}; + const PrivateAxiosInstance = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_BASE_URI, headers: { @@ -21,31 +32,32 @@ const PrivateAxiosInstance = axios.create({ }, }); +// 요청 인터셉터 PrivateAxiosInstance.interceptors.request.use( (config: InternalAxiosRequestConfig) => { const token = getAccessToken(); - if (!token) { - const redirectPages = ['/desktop/login', '/mobile/sign-in']; - const { pathname } = window.location; - - if (!redirectPages.includes(pathname)) { - window.location.replace( - pathname.startsWith('/desktop') - ? '/desktop/login' - : '/mobile/sign-in', - ); - } + if (!token) { + redirectToLogin(); return Promise.reject(new AxiosError('No authentication token found')); } const newConfig = { ...config, withCredentials: false }; - if (token) { - newConfig.headers.set('Authorization', `Bearer ${token}`); - } + newConfig.headers.set('Authorization', `Bearer ${token}`); return newConfig; }, (error) => Promise.reject(error), ); +PrivateAxiosInstance.interceptors.response.use( + (response) => response, + (error: AxiosError) => { + if (error.response?.status === 401) { + localStorage.clear(); + redirectToLogin(); + } + return Promise.reject(error); + }, +); + export default PrivateAxiosInstance;