import {qsparse, toast} from 'amis';
|
import axios, {CancelToken} from 'axios';
|
|
import qs from 'qs';
|
|
const MAIN_URL =
|
(window?.parent as any)?.globalConfig?.WebApiUrl?.MainUrl ??
|
'http://wi.cpolar.top';
|
//#region ====================== 后端 res.err_code ======================
|
export const enum ErrorCode {
|
/** @description 权限验证失败 */
|
Message = 'MESSAGE',
|
/** @description 内部错误 */
|
Exception = 'EXCEPTION',
|
/** @description 无权使用 */
|
Auth = 'AUTH'
|
}
|
//#endregion
|
// 配置新建一个 axios 实例
|
const createAxiosInstance = () => {
|
return axios.create({
|
baseURL: MAIN_URL,
|
timeout: 50000,
|
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
|
});
|
};
|
|
export type ExtraConfigData = {
|
cancelToken?: CancelToken | undefined;
|
};
|
// export const accessSessionKey = 'access-session';
|
const request = createAxiosInstance();
|
|
const handleNoAuth = () => {
|
(window.parent as any)?.handleNoAuth?.();
|
};
|
request.interceptors.request.use(
|
config => {
|
const paramsStr = location.href.split('?')[1];
|
const paramsSession =
|
paramsStr && (qs.parse(paramsStr).session as any)?.split('#')?.[0];
|
const accessSession = paramsSession;
|
if (accessSession) {
|
config.headers['hswatersession'] = accessSession;
|
} else {
|
handleNoAuth();
|
}
|
|
if (config.data) {
|
config.data = qs.stringify(config.data);
|
}
|
return config;
|
},
|
error => {
|
return Promise.reject(error);
|
}
|
);
|
|
request.interceptors.response.use(res => {
|
// 获取状态码和返回数据
|
const status = res.status;
|
const serveData = res.data;
|
|
if (!serveData) {
|
throw new Error('请求失败');
|
}
|
|
// 处理 401
|
if (status === 401) {
|
// clearAccessTokens();
|
}
|
|
// 响应拦截及自定义处理
|
if (!serveData.json_ok) {
|
switch (serveData?.err_code) {
|
case ErrorCode.Auth:
|
handleNoAuth();
|
throw '权限验证失败';
|
case ErrorCode.Exception:
|
// ElMessage.error('内部错误!');
|
toast.error('内部错误');
|
throw '内部错误';
|
}
|
// 非 message error,且 handleFail 为 true
|
// message error 不需要处理
|
if (serveData?.err_code !== ErrorCode.Message) {
|
const errorText = serveData?.json_msg || '响应失败!';
|
toast.error(errorText);
|
throw errorText;
|
}
|
}
|
return res.data;
|
});
|
|
export const getPageId = () => {
|
const str = window.location.href.split('?')[2];
|
let currentId: any;
|
if (str) {
|
const strObj = qsparse(str);
|
currentId = strObj?.id;
|
} else if ((window?.parent as any)?.currentPage?.id) {
|
currentId = (window?.parent as any)?.currentPage?.id;
|
} else {
|
const getId = localStorage.getItem('currentId');
|
currentId = getId;
|
}
|
localStorage.setItem('currentId', currentId);
|
return currentId;
|
};
|
|
export default request;
|