39 lines
1.5 KiB
TypeScript
39 lines
1.5 KiB
TypeScript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from "axios";
|
|
import formrHandle from "./format-handle";
|
|
import { debugUser } from "@/assets/config/api.config";
|
|
import conf from "@/assets/config/host.config";
|
|
import Utils from "@/utils";
|
|
|
|
export const initAxiosInstance: (config: AxiosRequestConfig) => AxiosInstance = config => {
|
|
let axiosInstance: AxiosInstance = axios.create(config);
|
|
|
|
axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
|
|
// if (config.params && typeof config.params != "string") config.params = utils.filterNull(config.params);
|
|
// 通用请求头:yschapirequest 标识 API 请求,yschreferer 记录来源页面(十六进制)
|
|
(config.headers as AxiosRequestHeaders)["yschapirequest"] = "1";
|
|
(config.headers as AxiosRequestHeaders)["yschreferer"] = Utils.strToHexCharCode(window.location.href);
|
|
|
|
if (localStorage.getItem("currentRole") != null) {
|
|
(config.headers as AxiosRequestHeaders)["currentRole"] = localStorage.getItem("currentRole") as string;
|
|
}
|
|
|
|
if (!!conf.isDebug) {
|
|
//如果是开发环境
|
|
for (const key in debugUser) (config.headers as AxiosRequestHeaders)[key] = (debugUser as any)[key];
|
|
}
|
|
|
|
return config;
|
|
});
|
|
|
|
axiosInstance.interceptors.response.use(
|
|
response => {
|
|
return formrHandle(response);
|
|
},
|
|
error => {
|
|
return formrHandle(error.response);
|
|
}
|
|
);
|
|
|
|
return axiosInstance;
|
|
};
|