2021-03-15 12:44:58 +08:00
|
|
|
import axios from 'axios';
|
|
|
|
import { ElMessage, ElMessageBox } from 'element-plus';
|
2021-06-19 17:49:42 +08:00
|
|
|
import { Session } from '/@/utils/storage';
|
2021-02-22 21:56:45 +08:00
|
|
|
|
|
|
|
// 配置新建一个 axios 实例
|
|
|
|
const service = axios.create({
|
2021-03-15 18:36:32 +08:00
|
|
|
baseURL: import.meta.env.VITE_API_URL as any,
|
2021-02-22 21:56:45 +08:00
|
|
|
timeout: 50000,
|
2021-03-15 12:44:58 +08:00
|
|
|
headers: { 'Content-Type': 'application/json' },
|
2021-02-22 21:56:45 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
// 添加请求拦截器
|
|
|
|
service.interceptors.request.use(
|
|
|
|
(config) => {
|
|
|
|
// 在发送请求之前做些什么 token
|
2021-06-19 17:49:42 +08:00
|
|
|
if (Session.get('token')) {
|
2022-02-25 23:19:12 +08:00
|
|
|
(<any>config.headers).common['Authorization'] = `${Session.get('token')}`;
|
2021-02-22 21:56:45 +08:00
|
|
|
}
|
2021-03-15 12:44:58 +08:00
|
|
|
return config;
|
2021-02-22 21:56:45 +08:00
|
|
|
},
|
|
|
|
(error) => {
|
|
|
|
// 对请求错误做些什么
|
2021-03-15 12:44:58 +08:00
|
|
|
return Promise.reject(error);
|
2021-02-22 21:56:45 +08:00
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
// 添加响应拦截器
|
|
|
|
service.interceptors.response.use(
|
|
|
|
(response) => {
|
|
|
|
// 对响应数据做点什么
|
2021-03-15 12:44:58 +08:00
|
|
|
const res = response.data;
|
2021-02-22 21:56:45 +08:00
|
|
|
if (res.code && res.code !== 0) {
|
|
|
|
// `token` 过期或者账号已在别处登录
|
|
|
|
if (res.code === 401 || res.code === 4001) {
|
2021-06-19 17:49:42 +08:00
|
|
|
Session.clear(); // 清除浏览器全部临时缓存
|
|
|
|
window.location.href = '/'; // 去登录页
|
2021-03-15 12:44:58 +08:00
|
|
|
ElMessageBox.alert('你已被登出,请重新登录', '提示', {})
|
|
|
|
.then(() => {})
|
|
|
|
.catch(() => {});
|
2021-02-22 21:56:45 +08:00
|
|
|
}
|
2021-03-15 12:44:58 +08:00
|
|
|
return Promise.reject(service.interceptors.response);
|
2021-02-22 21:56:45 +08:00
|
|
|
} else {
|
2021-03-15 12:44:58 +08:00
|
|
|
return response.data;
|
2021-02-22 21:56:45 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
(error) => {
|
|
|
|
// 对响应错误做点什么
|
2021-03-15 12:44:58 +08:00
|
|
|
if (error.message.indexOf('timeout') != -1) {
|
|
|
|
ElMessage.error('网络超时');
|
|
|
|
} else if (error.message == 'Network Error') {
|
|
|
|
ElMessage.error('网络连接错误');
|
2021-02-22 21:56:45 +08:00
|
|
|
} else {
|
2021-03-15 12:44:58 +08:00
|
|
|
if (error.response.data) ElMessage.error(error.response.statusText);
|
|
|
|
else ElMessage.error('接口路径找不到');
|
2021-02-22 21:56:45 +08:00
|
|
|
}
|
2021-03-15 12:44:58 +08:00
|
|
|
return Promise.reject(error);
|
2021-02-22 21:56:45 +08:00
|
|
|
}
|
|
|
|
);
|
|
|
|
|
2021-05-16 17:02:53 +08:00
|
|
|
// 导出 axios 实例
|
2021-03-15 12:44:58 +08:00
|
|
|
export default service;
|