Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/apis/item.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -13,6 +14,9 @@ export const getWelfareItems = async (

return response.data;
} catch (error) {
if (isAxiosError(error)) {
console.log(error);
}
throw new Error(`welfare 목록 불러오기에 실패했습니다: ${error}`);
}
};
40 changes: 26 additions & 14 deletions src/services/privateAxiosInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,50 @@ 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: {
'Content-Type': 'application/json',
},
});

// 요청 인터셉터
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;