64 lines
1.4 KiB
JavaScript
64 lines
1.4 KiB
JavaScript
import axios from 'axios';
|
|
import store from '../store';
|
|
import router from '../router';
|
|
import { HTTP_BASE_URL } from "./config"
|
|
|
|
let redirectingToLogin = false;
|
|
|
|
function redirectToLogin() {
|
|
if (redirectingToLogin || router.currentRoute.path === '/login') {
|
|
return;
|
|
}
|
|
|
|
redirectingToLogin = true;
|
|
router.replace('/login').then(
|
|
() => {
|
|
redirectingToLogin = false;
|
|
},
|
|
(navigationError) => {
|
|
redirectingToLogin = false;
|
|
if (navigationError.name !== 'NavigationDuplicated') {
|
|
console.error(navigationError);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
// 配置请求
|
|
const request = axios.create({
|
|
baseURL: HTTP_BASE_URL,
|
|
timeout: 10000,
|
|
});
|
|
|
|
// 请求拦截器:每次请求都带上token
|
|
request.interceptors.request.use(
|
|
(config) => {
|
|
// 在请求头中添加token
|
|
const token = localStorage.getItem('token');
|
|
if (token) {
|
|
config.headers['Authorization'] = `${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
request.interceptors.response.use(
|
|
(response) => {
|
|
return response.data;
|
|
},
|
|
(error) => {
|
|
if (error.response && error.response.status === 401) {
|
|
// 如果返回401,说明token过期或无效,清除token并跳转到登录页
|
|
store.commit('SET_TOKEN', '');
|
|
store.commit('SET_USERNAME', '');
|
|
redirectToLogin();
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default request;
|