2023-03-29 14:04:51 +08:00
|
|
|
import axios from 'axios';
|
|
|
|
import { ElMessage, ElMessageBox } from 'element-plus';
|
|
|
|
import qs from 'qs';
|
|
|
|
import { Session } from '/@/utils/storage';
|
|
|
|
|
|
|
|
// 配置新建一个 axios 实例
|
|
|
|
const service = axios.create({
|
|
|
|
//baseURL: import.meta.env.VITE_API_URL,
|
|
|
|
timeout: 50000,
|
|
|
|
headers: { 'Content-Type': 'application/json' },
|
|
|
|
paramsSerializer: {
|
|
|
|
serialize(params) {
|
|
|
|
return qs.stringify(params, { allowDots: true });
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
// 添加请求拦截器
|
|
|
|
service.interceptors.request.use(
|
|
|
|
(config) => {
|
2023-03-30 16:45:56 +08:00
|
|
|
config.headers['Authorization'] = 'Basic Vm9SRE1BZG1pbjp2b3JkbV9hZG1pbl9zZWNyZXQ=';
|
2023-03-29 14:04:51 +08:00
|
|
|
// 在发送请求之前做些什么 token
|
|
|
|
if (Session.get('token')) {
|
2023-03-30 16:45:56 +08:00
|
|
|
config.headers['Blade-Auth'] = `Bearer ${Session.get('token')}`;
|
2023-03-29 14:04:51 +08:00
|
|
|
}
|
|
|
|
return config;
|
|
|
|
},
|
|
|
|
(error) => {
|
|
|
|
// 对请求错误做些什么
|
|
|
|
return Promise.reject(error);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
// 添加响应拦截器
|
|
|
|
service.interceptors.response.use(
|
|
|
|
(response) => {
|
|
|
|
// 对响应数据做点什么
|
|
|
|
const res = response.data;
|
2023-03-30 16:45:56 +08:00
|
|
|
if (res.code && res.code !== 200) {
|
2023-03-29 14:04:51 +08:00
|
|
|
// `token` 过期或者账号已在别处登录
|
|
|
|
if (res.code === 401 || res.code === 4001) {
|
|
|
|
Session.clear(); // 清除浏览器全部临时缓存
|
|
|
|
window.location.href = '/'; // 去登录页
|
|
|
|
ElMessageBox.alert('你已被登出,请重新登录', '提示', {})
|
|
|
|
.then(() => {})
|
|
|
|
.catch(() => {});
|
2023-03-30 16:45:56 +08:00
|
|
|
} else if(res.code === 400){
|
|
|
|
ElMessage.error(res.msg)
|
2023-03-29 14:04:51 +08:00
|
|
|
}
|
|
|
|
return Promise.reject(service.interceptors.response);
|
|
|
|
} else {
|
2023-03-30 16:45:56 +08:00
|
|
|
return res.data || res;
|
2023-03-29 14:04:51 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
(error) => {
|
|
|
|
// 对响应错误做点什么
|
|
|
|
if (error.message.indexOf('timeout') != -1) {
|
|
|
|
ElMessage.error('网络超时');
|
|
|
|
} else if (error.message == 'Network Error') {
|
|
|
|
ElMessage.error('网络连接错误');
|
|
|
|
} else {
|
2023-03-30 16:45:56 +08:00
|
|
|
if( error.response.data.error_description ) ElMessage.error(error.response.data.error_description);
|
|
|
|
//if (error.response.data) ElMessage.error(error.response.statusText);
|
2023-03-29 14:04:51 +08:00
|
|
|
else ElMessage.error('接口路径找不到');
|
|
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
// 导出 axios 实例
|
|
|
|
export default service;
|