154 lines
5.1 KiB
TypeScript
154 lines
5.1 KiB
TypeScript
import { ref } from 'vue';
|
|
import axios, { AxiosRequestConfig } from 'axios';
|
|
import qs from 'qs';
|
|
import { showToast, showLoadingToast, closeToast } from 'vant';
|
|
import { ContentTypeEnum } from './httpEnum';
|
|
import { useUserStore } from '@/store/modules/user';
|
|
import { getLogin } from '@/api/demo';
|
|
// import router from '@/router';
|
|
|
|
// 超文本传输协议
|
|
let href = ref('http:');
|
|
if (location.href.includes('https:')) {
|
|
href.value = 'https:';
|
|
}
|
|
|
|
// 创建一个axios实例
|
|
const service = axios.create({
|
|
baseURL: `${href.value}${import.meta.env.VITE_BASE_API as string}`,
|
|
withCredentials: false, // 当跨域请求时发送cookie
|
|
timeout: 15000, // 请求超时时间
|
|
});
|
|
|
|
interface CustomAxiosRequestConfig extends AxiosRequestConfig {
|
|
hideLoading?: boolean;
|
|
}
|
|
|
|
interface BaseResponse<T = any> {
|
|
code: number;
|
|
data: T;
|
|
msg: string;
|
|
}
|
|
|
|
// request请求拦截器
|
|
service.interceptors.request.use(
|
|
(config: CustomAxiosRequestConfig) => {
|
|
// 不传递默认开启loading
|
|
if (!config.hideLoading) {
|
|
showLoadingToast({
|
|
message: '加载中...',
|
|
forbidClick: true,
|
|
});
|
|
}
|
|
const userStore = useUserStore() as any;
|
|
if (import.meta.env.MODE === 'development') {
|
|
userStore.chatId = 1;
|
|
}
|
|
if ((localStorage.getItem('workToken') || userStore.token) && config.headers) {
|
|
config.headers['Authorization'] = `Bearer ${localStorage.getItem('workToken') || userStore.token}`;
|
|
}
|
|
if (config.headers) {
|
|
config.headers['Version'] = `${import.meta.env.VITE_BASE_API_VERSION}`;
|
|
}
|
|
if (config.url?.includes('?')) {
|
|
config.url = `${config.url}&work_id=${localStorage.getItem('work_id') || ''}`;
|
|
} else {
|
|
config.url = `${config.url}?work_id=${localStorage.getItem('work_id') || ''}`;
|
|
}
|
|
const contentType = config.headers?.['content-type'] || config.headers?.['Content-Type'];
|
|
const data = config.data;
|
|
if (config.method?.toLocaleUpperCase() == 'POST' && data) {
|
|
if (ContentTypeEnum.FORM_DATA == contentType) {
|
|
const fd = new FormData();
|
|
Object.keys(data).forEach((key) => fd.append(key, data[key]));
|
|
config.data = fd;
|
|
} else if (ContentTypeEnum.FORM_URLENCODED == contentType) {
|
|
config.data = qs.stringify(config.data);
|
|
}
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
// 处理请求错误
|
|
console.log(error);
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
// response相应拦截器
|
|
const error = ref(1);
|
|
const errorV3 = ref(1);
|
|
service.interceptors.response.use(
|
|
(response) => {
|
|
closeToast();
|
|
const userStore = useUserStore();
|
|
const res = response.data;
|
|
if (res.code === 1) {
|
|
// 服务器访问出错了~
|
|
showToast(res.message);
|
|
return Promise.reject(res.message || 'code: 1');
|
|
} else if (res.code === 2) {
|
|
// 登录超时,重新登录
|
|
error.value += 1;
|
|
if (error.value <= 2) {
|
|
// 本地环境
|
|
if (import.meta.env.MODE === 'development') {
|
|
userStore.token = '53|SPv38Y7yBN7AFglo82Cze3hU1qVqJPL8QUG4UDen';
|
|
} else {
|
|
localStorage.removeItem('workToken');
|
|
localStorage.removeItem('work_id');
|
|
getLogin().then((res) => {
|
|
let result = res.data;
|
|
localStorage.setItem('workToken', result.user ? result.user.token : '');
|
|
localStorage.setItem('work_id', result.user ? result.user.work_id : '');
|
|
userStore.token = result.user ? result.user.token : '';
|
|
userStore.name = result.user ? result.user.name : '';
|
|
userStore.mobile = result.user ? result.user.mobile : '';
|
|
userStore.avatar = result.user ? result.user.avatar : 'http://images.ufutx.com/201905/13/599151d27fc07ba1bc4cc57a291525e5.jpeg';
|
|
setTimeout(() => {
|
|
window.location.replace(location.href);
|
|
}, 200);
|
|
});
|
|
}
|
|
}
|
|
return Promise.reject(res.message);
|
|
} else if (res.code === 3) {
|
|
errorV3.value += 1;
|
|
if (errorV3.value <= 2) {
|
|
// 本地环境
|
|
if (import.meta.env.MODE === 'development') {
|
|
userStore.token = '53|SPv38Y7yBN7AFglo82Cze3hU1qVqJPL8QUG4UDen';
|
|
} else {
|
|
// master环境
|
|
if (location.href.split('/#/')[1]) {
|
|
window.location.replace(`https://health.ufutx.com/api/h5/order/bound/enterprise/auth/v2?target_path=/work/#/${location.href.split('/#/')[1]}`);
|
|
} else {
|
|
window.location.replace(`https://health.ufutx.com/api/h5/order/bound/enterprise/auth/v2?target_path=/work/#/h5/boundEnterprise`);
|
|
}
|
|
}
|
|
}
|
|
return Promise.resolve(response);
|
|
} else {
|
|
return Promise.resolve(response);
|
|
}
|
|
},
|
|
(error: Error) => {
|
|
if (error.message?.includes('timeout')) {
|
|
showToast('请求超时!');
|
|
}
|
|
console.log(`err${error}`);
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
const request = <T = any>(config: CustomAxiosRequestConfig): Promise<BaseResponse<T>> => {
|
|
return new Promise((resolve, reject) => {
|
|
service
|
|
.request<BaseResponse<T>>(config)
|
|
.then((res) => resolve(res.data))
|
|
.catch((err) => reject(err));
|
|
});
|
|
};
|
|
|
|
export default request;
|