import store from '@/store/index';
import router from '@/routes/index';
import axios from 'axios';
import { saveAuthToCookie, deleteCookie } from '@/utils/cookies';
import { instance as newInstance } from '@/api/index';
axios.defaults.withCredentials = true;
export function setInterceptors(instance) {
// Add a request interceptor
instance.interceptors.request.use(
function (config) {
// Do something before request is sent
// console.log(config);
config.headers.Authorization = 'Bearer ' + store.state.token;
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
},
);
// Add a response interceptor
instance.interceptors.response.use(
function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
const originalConfig = error.response.config;
console.log('originalConfig : ', originalConfig);
const status = error.response.status;
const message = error.response.data.message;
//토큰 만료시 refreshtoken으로 토큰 연장
if (status == 401 && message == 'TokenExpiredError') {
axios
.post(`${process.env.VUE_APP_API_URL}auth/refreshToken`, {})
.then(function (response) {
deleteCookie('til_auth');
saveAuthToCookie(response.data);
store.commit('setToken', response.data);
// originalConfig._retry = true;
originalConfig.headers.Authorization = `Bearer ${response.data}`;
return newInstance(originalConfig);
})
.catch(function (error) {
console.log(error.response);
alert('인증이 완료되었습니다. 로그인 해주세요');
//state 삭제
// store.commit('clearUsername');
// store.commit('clearToken');
// //쿠키값 삭제
// deleteCookie('til_auth');
// deleteCookie('til_user');
//refreshtoken 만료 또는 없을때 로그인 화면으로 이동
if (error.response.status == 500) {
router.push('/login');
}
});
} else if (status == 403) {
console.log('403 에러');
alert('권한이 없습니다.');
}
return Promise.reject(error);
},
);
return instance;
}
답변 1