72 lines
1.8 KiB
TypeScript
72 lines
1.8 KiB
TypeScript
import axios from 'axios';
|
|
import { Modal, notification } from 'ant-design-vue';
|
|
import router from '@/router';
|
|
import { getToken } from '@/utils/auth';
|
|
|
|
const errCodeMap: { [key: string]: string } = {
|
|
'403': '当前操作没有权限',
|
|
'404': '访问资源不存在',
|
|
'default': '系统未知错误,请反馈给管理员'
|
|
};
|
|
|
|
// 创建axios实例
|
|
const service = axios.create({
|
|
baseURL: import.meta.env.VITE_APP_BASE_API as string,
|
|
timeout: 10000
|
|
});
|
|
|
|
// 请求拦截器
|
|
service.interceptors.request.use(
|
|
config => {
|
|
config.headers = config.headers || {};
|
|
config.headers['Accept-Language'] = 'zh-CN';
|
|
|
|
const token = getToken();
|
|
if (token) {
|
|
config.headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
error => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// 响应拦截器
|
|
service.interceptors.response.use(
|
|
response => {
|
|
console.log(response)
|
|
// 未设置状态码则默认成功状态
|
|
const code = response.data.code || 200;
|
|
|
|
if (code === 200) {
|
|
return response.data ?? response;
|
|
} else if (code === 401) {
|
|
Modal.error({
|
|
title: '系统提示',
|
|
content: '登录状态已过期,请重新登录',
|
|
onOk: () => {
|
|
router.push('/login')
|
|
}
|
|
})
|
|
} else {
|
|
const codeStr = String(code);
|
|
const errMsg = errCodeMap[codeStr] || response.data.msg || errCodeMap['default'];
|
|
notification.error({
|
|
message: '请求错误',
|
|
description: errMsg,
|
|
});
|
|
return Promise.reject(response.data);
|
|
}
|
|
},
|
|
error => {
|
|
// 网络/服务器错误统一处理
|
|
notification.error({
|
|
message: '网络错误',
|
|
description: error.message || '请求失败',
|
|
});
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default service; |