2021-03-15 12:44:58 +08:00
|
|
|
import axios from 'axios';
|
|
|
|
import { ElMessage, ElMessageBox } from 'element-plus';
|
|
|
|
import { clearSession, getSession } from '/@/utils/storage.ts';
|
|
|
|
import router, { resetRoute } from '/@/router/index.ts';
|
2021-02-22 21:56:45 +08:00
|
|
|
|
|
|
|
// 配置新建一个 axios 实例
|
|
|
|
const service = axios.create({
|
|
|
|
baseURL: 'http://localhost:10000/',
|
|
|
|
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-03-15 12:44:58 +08:00
|
|
|
if (getSession('token')) {
|
|
|
|
config.headers.common['Authorization'] = `${getSession('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) {
|
|
|
|
clearSession(); // 清除浏览器全部临时缓存
|
2021-03-15 12:44:58 +08:00
|
|
|
router.push('/login'); // 去登录页面
|
|
|
|
resetRoute(); // 删除/重置路由
|
|
|
|
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-03-15 12:44:58 +08:00
|
|
|
export default service;
|