init
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// 환경 변수에서 API URL을 가져오거나 기본값 사용
|
||||
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3030';
|
||||
|
||||
// axios 인스턴스 생성
|
||||
const apiClient = axios.create({
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 10000
|
||||
});
|
||||
|
||||
// 요청 인터셉터 - 토큰 추가
|
||||
apiClient.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// 응답 인터셉터 - 에러 처리
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
return response;
|
||||
},
|
||||
(error) => {
|
||||
// 401 에러 (인증 실패) 처리
|
||||
if (error.response && error.response.status === 401) {
|
||||
// 로컬 스토리지에서 토큰 제거
|
||||
localStorage.removeItem('token');
|
||||
// 로그인 페이지로 리디렉션
|
||||
window.location.href = '/login';
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
Reference in New Issue
Block a user