39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
import { BASE_URL } from '@/helpers/constants';
|
|
import { auth_service } from '@/services/auth';
|
|
import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
|
|
|
|
const myAxios: AxiosInstance = axios.create({
|
|
baseURL: BASE_URL,
|
|
timeout: 10000,
|
|
});
|
|
|
|
myAxios.interceptors.request.use(
|
|
(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
|
|
const token = localStorage.getItem('token');
|
|
if (token) {
|
|
config.headers = config.headers || {};
|
|
config.headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
error => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
myAxios.interceptors.response.use(
|
|
(response: AxiosResponse) => {
|
|
return response.data;
|
|
},
|
|
error => {
|
|
if (error.response?.status === 401) {
|
|
// localStorage.removeItem('token');
|
|
// window.location.href = '/';
|
|
auth_service.logout();
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default myAxios;
|