118 lines
2.7 KiB
TypeScript
118 lines
2.7 KiB
TypeScript
import { i18n } from '@/locale/index.ts';
|
|
import { getToken, clearToken } from '@/utils/const';
|
|
|
|
const t: any = i18n.global.t;
|
|
let baseURL: string;
|
|
|
|
// #ifndef H5
|
|
console.log('------非H5------');
|
|
baseURL = 'https://user.htltd.net/api';
|
|
// baseURL = 'http://192.168.123.247:8080';
|
|
// #endif
|
|
|
|
// #ifdef H5
|
|
console.log('------H5------');
|
|
baseURL = 'http://localhost:8080';
|
|
// #endif
|
|
// const baseURL = 'http://47.238.103.157:81';
|
|
const proxyMap = { '/api': baseURL, '/api2': 'http://8.212.58.187:32249' };
|
|
const proxy = (url: string) => {
|
|
let target = url;
|
|
// #ifndef H5
|
|
const tags = Object.keys(proxyMap);
|
|
tags.find((tag) => {
|
|
if (!tag.startsWith('/')) return;
|
|
if (url.startsWith(tag + '/')) {
|
|
target = proxyMap[tag] + url.replace(tag, '');
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
});
|
|
// #endif
|
|
return target;
|
|
};
|
|
|
|
const httpInterceptor = {
|
|
invoke(options: UniApp.RequestOptions) {
|
|
if (!options.url.startsWith('http')) {
|
|
options.url = proxy(options.url);
|
|
}
|
|
options.timeout = 180000;
|
|
options.header = {
|
|
...options.header
|
|
};
|
|
const token = getToken();
|
|
if (token) {
|
|
options.header.Authorization = token;
|
|
}
|
|
}
|
|
};
|
|
|
|
uni.addInterceptor('request', httpInterceptor);
|
|
uni.addInterceptor('uploadFile', httpInterceptor);
|
|
|
|
interface Data<T> {
|
|
code: number;
|
|
msg: string;
|
|
result: T;
|
|
}
|
|
export const request = <T>(options: UniApp.RequestOptions) => {
|
|
return new Promise<Data<T>>((resolve, reject) => {
|
|
uni.request({
|
|
...options,
|
|
success: (res) => {
|
|
// 状态码2xx
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
resolve(res.data as Data<T>);
|
|
} else if (res.statusCode === 401) {
|
|
uni.showToast({
|
|
icon: 'none',
|
|
title: t('common.error.401')
|
|
});
|
|
clearToken();
|
|
uni.navigateTo({ url: '/pages/login/index' });
|
|
resolve({ code: res.statusCode } as Data<T>);
|
|
} else {
|
|
reject(res);
|
|
}
|
|
},
|
|
fail(err) {
|
|
uni.showToast({
|
|
icon: 'none',
|
|
title: 'NetWork ERROR'
|
|
});
|
|
reject(err);
|
|
}
|
|
});
|
|
});
|
|
// return uni.request({
|
|
// ...options,
|
|
// success: (res) => {
|
|
// // 状态码2xx
|
|
// if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
// return res.data as Data<T>;
|
|
// } else if (res.statusCode === 401) {
|
|
// const userStore = useUserStore();
|
|
// userStore.clear();
|
|
// uni.navigateTo({ url: '/pages/login/index' });
|
|
// return res;
|
|
// } else {
|
|
// uni.showToast({
|
|
// icon: 'none',
|
|
// title: t(`errorMsg.${res.statusCode}`)
|
|
// });
|
|
// return res;
|
|
// }
|
|
// },
|
|
// fail(err) {
|
|
// uni.showToast({
|
|
// icon: 'none',
|
|
// title: '网络连接失败,请稍后再试'
|
|
// });
|
|
// return err;
|
|
// }
|
|
// });
|
|
};
|
|
|
|
export const app_host = baseURL; |