You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
shop-admin/src/utils/request.js

91 lines
3.0 KiB

import config from '@/configs';
import { ElMessage } from '@/plugins/element-plus';
import store from '@/store';
import qs from 'qs';
const handleResponse = async ({ config: requestConfig, data, status }) => {
if (requestConfig.headers.oss === true) {
return `${requestConfig.url}/${requestConfig.data
.get('key')
.replace('${filename}', requestConfig.data.get('name'))}`;
}
if (requestConfig.headers.download === true) {
return data;
}
let code = data?.code || status;
console.info('[api]', code, requestConfig.method, requestConfig.url, data?.data);
if (code !== 'SUCCESS') {
ElMessage.error(data?.message || '服务器异常');
if (data) {
data.data = null;
}
switch (code) {
case 'SYSTEM_ERROR': //系统异常
case 'INTERFACE_SYSTEM_ERROR': // 外部接口调用异常
case 'CONNECT_TIME_OUT': // 业务连接处理超时
case 'NULL_ARGUMENT': // 参数为空
case 'ILLEGAL_ARGUMENT': // 参数不合法
case 'ILLEGAL_CONFIGURATION': // 非法配置
case 'ILLEGAL_STATE': // 非法状态
case 'ENUM_CODE_ERROR': // 错误的枚举编码
case 'LOGIC_ERROR': // 逻辑错误
case 'CONCURRENT_ERROR': // 并发异常
case 'ILLEGAL_OPERATION': // 非法操作
case 'REPETITIVE_OPERATION': // 重复操作
case 'RESOURCE_NOT_FOUND': // 资源不存在
case 'RESOURCE_ALREADY_EXIST': // 资源已存在
case 'TYPE_UN_MATCH': // 类型不匹配
case 'FILE_NOT_EXIST': // 文件不存在
case 'LIMIT_BLOCK': // 请求被限流
case 'BIZ_ERROR': // 业务处理异常
case 'NO_OPERATE_PERMISSION': // 无操作权限
default:
break;
case 'TOKEN_EXPIRE': // TOKEN过期
case 'TOKEN_FAIL': // TOKEN失效
store.dispatch('auth/logout');
break;
}
}
return data?.data;
};
const instance = axios.create({
baseURL: config.baseURL,
timeout: config.requestTimeout,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
});
instance.interceptors.request.use(
(config) => {
const token = store.state.local.token;
if (token) {
config.headers['Authorization'] = token;
}
if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') {
config.data = qs.stringify(config.data);
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => handleResponse(response),
(error) => {
let res = null;
if (!error.response) {
ElMessage.error(error.message || '请求失败');
} else {
res = handleResponse(error.response);
}
return res;
}
);
export default instance;