import { useUserStore } from '@/store/user'; export const baseUrl = import.meta.env.VITE_APP_BASE_URL; const appVersion = uni.getSystemInfoSync().appVersion; // 添加拦截器 // const httpInterceptor = { // // 拦截前触发 // invoke(options) { // // 1. 非 http 开头需拼接地址 // if (!options.url.startsWith('http')) { // options.url = baseUrl + options.url; // } // // 2. 请求超时, 默认 10s // options.timeout = 10000; // options.header = { // ...options.header, // 'Content-Type': 'application/x-www-form-urlencoded', // }; // const userStore = useUserStore(); // options.data = { // ...options.data, // __token: userStore.userToken, // __platform: userStore.platform, // }; // }, // }; // uni.addInterceptor('request', httpInterceptor); // // #ifndef H5 // uni.addInterceptor('uploadFile', httpInterceptor); // // #endif // 对uni原生的request做的一个封装 export const request = (options = {}) => { return new Promise((resolve, reject) => { const userStore = useUserStore(); // 请求头 options.header = { 'Content-Type': 'application/x-www-form-urlencoded', // version: appVersion, }; var params = { __token: userStore.userToken, __platform: userStore.platform, __language: userStore.lang, __channelId: 33, }; var data = options.data; data = { ...data, ...params, }; // uni原生request uni .request({ url: baseUrl + options.url || '', method: options.method || 'GET', data: data || {}, header: options.header || {}, }) .then((res) => { if (res.statusCode === 401) { // usetToken无效,移除本地缓存 userStore.userToken = ''; userStore.clearProfile(); userStore.isLogin = false; resolve({ ...res.data, statusCode: res.statusCode, }); } else { resolve({ ...res.data, statusCode: res.statusCode, }); } }) .catch((error) => { if (error.statusCode === 401) { // usetToken无效,移除本地缓存 userStore.userToken = ''; userStore.clearProfile(); reject({ ...error.data, statusCode: error.statusCode, }); } else { uni.showToast({ duration: 2500, icon: 'none', mask: true, title: 'Server exception, please try again later', }); setTimeout(() => { uni.hideLoading(); reject(error.data); }, 2000); } }); }); }; // 定义get请求 export const get = (url, data = {}, options = {}) => { options.url = url; options.method = 'GET'; options.data = data; return request(options); }; // 定义post请求 export const post = (url, data = {}, options = {}) => { options.url = url; options.method = 'POST'; options.data = data; return request(options); }; // 定义put请求 export const put = (url, data = {}, options = {}) => { options.url = url; options.method = 'PUT'; options.data = data; return request(options); }; // 定义delete请求 export const dele = (url, data = {}, options = {}) => { options.url = url; options.method = 'DELETE'; options.data = data; return request(options); };