import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessageBox, ElLoading, ElMessage } from "element-plus";
import { LoadingInstance } from "element-plus/lib/components/loading/src/loading";
import router from "../router";
import { PRIFIX } from "../../public/config";
//消息提示
type Message =
| boolean
| {
error: boolean | string;
success: boolean | string;
};
// loading
type Loading = boolean | LoadingInstance | string;
//请求参数
export interface RequestConfigOption
extends AxiosRequestConfig,
Record<string, any> {
//请求类型
requestType?: "form" | "json" | "file";
//是否loading
loading?: Loading;
//是否消息提示
message?: Message;
}
//处理提示参数
const processMessageOptions = (message: Message) => {
if (typeof message == "boolean") {
return { error: message, success: message };
} else if (typeof message == "object") {
return message;
}
return { error: false, success: false };
};
//ContentType 映射
const ContentTypeMap = {
form: "application/x-www-form-urlencoded",
file: "multipart/form-data",
json: "application/json",
};
//处理header
const processHeader = (option: RequestConfigOption) => {
const { requestType } = option;
option.headers = option.headers || {};
if (requestType && ContentTypeMap[requestType]) {
option.headers["Content-Type"] = ContentTypeMap[requestType];
}
return option;
};
//处理loading参数
const processLoadingOptions = (loading: Loading) => {
if (typeof loading == "boolean" && loading) {
return { lock: true, text: "加载中" };
} else if (typeof loading == "string") {
return { lock: true, text: loading };
} else if (typeof loading == "object") {
return loading;
}
return false;
};
export const genHttp = (prefix: string) => {
const instance = axios.create({
baseURL: ("/" + prefix).replace(/\/\//g, "/"),
// timeout: 120000,
timeout: 1800000,
});
// 添加请求拦截器
instance.interceptors.request.use(
(config: RequestConfigOption) => {
console.log("config", config);
//处理头部
processHeader(config);
const urls = ["oauth/token"];
const inUrl = urls.some((url) => config.url?.includes(url));
if (!inUrl) {
Object.assign(config.headers, {
Authorization: localStorage.getItem("webtoken"),
siteType: "web",
userId: localStorage.getItem("webuser")
? JSON.parse(localStorage.getItem("webuser")).id
: "",
supplierCode: localStorage.getItem("supplierCode") || "",
});
} else {
Object.assign(config.headers, {
Authorization: config.Authorization,
siteType: "web",
userId: localStorage.getItem("webuser")
? JSON.parse(localStorage.getItem("webuser")).id
: "",
supplierCode: localStorage.getItem("supplierCode") || "",
});
}
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
async (response: AxiosResponse<BaseResponse<any>>) => {
// 对响应数据做点什么
const { status, data = {} as any } = response;
if (status == 200) {
interceptorFun(data);
//兼容平台端的响应结构不规范
if (!data.hasOwnProperty("success") || !data.hasOwnProperty("code")) {
return Promise.resolve(response.data);
}
if (data.success) {
return Promise.resolve(response.data);
}
} else if (status == 500) {
ElMessage.error("系统异常");
}
return Promise.reject(data);
},
(error: AxiosError) => {
if (error.response) {
const { status, data = {} } = error.response;
if (status == 401) {
//客户端不给任何提示
localStorage.setItem("tokenVaild", "");
const haveTip = localStorage.getItem("haveTip") || "";
if (!haveTip) {
localStorage.setItem("haveTip", "1");
ElMessageBox.alert("登录失效,前往登录页面", "提示", {
confirmButtonText: "确定",
showClose: false,
callback: (action: any) => {
router.push({ path: "/login" });
localStorage.setItem("haveTip", "");
},
});
}
// router.push({name:'init', query: { redirect: encodeURIComponent(window.location.href) } });
// router.push({path: "/login"});
return Promise.reject({
message: "登录失效",
});
}
// 对响应错误做点什么
return Promise.reject({
...data,
message: data.message || data.error_description,
});
}
// 对响应错误做点什么
return Promise.reject({});
}
);
//基础请求
const request = (
promise: Promise<BaseResponse<any>>,
options?: RequestConfigOption
) => {
options = options || {};
//解析loading参数
const loadingOptions = processLoadingOptions(options.loading as Loading);
loadingOptions &&
(options.$loading = ElLoading.service(loadingOptions as any));
//解析message参数
const messageOptions = processMessageOptions(options.message as Message);
const getMessageStr = (value, defaultStr) => {
return typeof value == "boolean" ? defaultStr : value;
};
return promise
.then((res) => {
const { message } = res;
messageOptions.success &&
ElMessage.success(
getMessageStr(messageOptions.success, message || "操作成功")
);
return Promise.resolve(res);
})
.catch((res) => {
const { message } = res;
messageOptions.error &&
ElMessage.error(
getMessageStr(messageOptions.error, message || "操作失败")
);
return Promise.reject(res);
})
.finally(() => {
options?.$loading?.close();
});
};
const http = {
get<T = any>(
url: string,
data?: Record<string, any>,
options?: RequestConfigOption
): Promise<BaseResponse<T>> {
return request(
instance.get(url, { params: data || {}, ...options }),
options
);
},
post<T = any>(
url: string,
data?: Record<string, any>,
options?: RequestConfigOption
): Promise<BaseResponse<T>> {
return request(instance.post(url, data, { ...options }), options);
},
put<T = any>(
url: string,
data?: Record<string, any>,
options?: RequestConfigOption
): Promise<BaseResponse<T>> {
return request(instance.put(url, data, { ...options }), options);
},
delete<T = any>(
url: string,
data?: Record<string, any>,
options?: RequestConfigOption
): Promise<BaseResponse<T>> {
return request(
instance.delete(url, {
params: data || {},
...options,
}),
options
);
},
};
return http;
};
// 返回状态码拦截判断
const interceptorFun = (data: any) => {
const status = data.status;
if (status == 4000) {
// 注册成功没有签合同
router.push({ path: "/signingPage" });
} else if (status == 4001) {
// 合同审核中
router.push({ path: "/onlineSign" });
} else if (status == 4002) {
// 合同审核不通过
router.push({ path: "/onlineSign" });
} else if (status == 4003) {
// 合同审核通过,未支付
router.push({ path: "/onlineSign" });
} else if (status == 4004) {
// 合同审核通过,支付审核中
router.push({ path: "/onlinePay" });
} else if (status == 4005) {
// 合同审核通过,支付审核不通过
router.push({ path: "/onlinePay" });
} else if (status == 4006) {
// 合同审核通过,支付审核通过
}
};
//默认http
const http = genHttp(PRIFIX + "");
// const http = genHttp("/dsj-system");
//大厅
export const hallHttp = genHttp(PRIFIX + "/dsj-gpd-hall");
//云桌面
export const superCounterHttp = genHttp(PRIFIX + "/dsj-gpd-super-counter");
//事项
export const itemHttp = genHttp(PRIFIX + "/dsj-gpd-item");
//文件服务
export const fileHttp = genHttp(PRIFIX + "/dsj-file");
//combo服务
export const comboHttp = genHttp(PRIFIX + "/dsj-gpb-combo");
// dsj-business服务
export const businessHttp = genHttp("/dsj-business");
export default http;
外部写个通用方法把get请求参数拼接在URL
//api公共工具类
export default {
getUrl(url: string, params: any) {
if (params) {
Object.keys(params).map((key, index) => {
const pre = index == 0 ? "?" : "&";
let val = params[key];
if (val == null) val = "";
url += `${pre}${key}=${val}`;
});
}
return url;
},
};