// 平台适配配置 const PLATFORM_CONFIG = { 'mp-weixin': { // 微信小程序 storageKey: 'wx_token', authHeader: 'Authorization', baseURL: 'https://api.weixin.example.com' }, 'mp-kuaishou': { // 快手小程序 storageKey: 'ks_token', authHeader: 'X-KS-Token', baseURL: 'https://api.kuaishou.example.com' } }; // 获取当前平台配置 function getPlatformConfig() { const platform = process.env.VUE_APP_PLATFORM; return PLATFORM_CONFIG[platform] || { storageKey: 'token', authHeader: 'Authorization', baseURL: 'https://api.example.com' }; } // 请求拦截器 const requestInterceptor = (config) => { const platformConfig = getPlatformConfig(); // 添加token const token = uni.getStorageSync(platformConfig.storageKey); if (token) { config.header[platformConfig.authHeader] = `Bearer ${token}`; } // 添加通用头 config.header['Content-Type'] = 'application/json'; // 添加平台标识 config.header['X-Platform'] = process.env.VUE_APP_PLATFORM; // 处理URL if (!config.url.startsWith('http')) { config.url = `${platformConfig.baseURL}${config.url}`; } console.log('[Request]', config.method, config.url); return config; }; // 响应拦截器 const responseInterceptor = (response) => { console.log('[Response]', response.statusCode, response.data); // 响应成功处理 if (response.statusCode >= 200 && response.statusCode < 300) { // 添加业务状态码处理逻辑 if (response.data.code === 200) { return response.data; } else { // 业务错误处理 return Promise.reject({ code: response.data.code, message: response.data.msg || '业务逻辑错误' }); } } // HTTP错误处理 const errorMap = { 400: '请求参数错误', 401: '登录已过期,请重新登录', 403: '拒绝访问', 404: '请求地址错误', 500: '服务器内部错误' }; const errorMessage = errorMap[response.statusCode] || `服务器错误: ${response.statusCode}`; // 401特殊处理 if (response.statusCode === 401) { uni.removeStorageSync(getPlatformConfig().storageKey); uni.showToast({ title: '登录已过期,请重新登录', icon: 'none', complete: () => { setTimeout(() => { uni.redirectTo({ url: '/pages/login/login' }); }, 1500); } }); } return Promise.reject({ code: response.statusCode, message: errorMessage }); }; // 错误处理 const errorHandler = (error) => { console.error('[Error]', error); // 统一错误提示 let errorMessage = error.message || '未知错误'; // 网络错误特殊处理 if (error.errMsg && error.errMsg.indexOf('request:fail') !== -1) { errorMessage = '网络连接失败,请检查网络设置'; } uni.showToast({ title: errorMessage, icon: 'none', duration: 3000 }); return Promise.reject(error); }; // 创建请求实例 const createRequest = () => { // 平台检查 const platform = process.env.VUE_APP_PLATFORM; if (!platform || !Object.keys(PLATFORM_CONFIG).includes(platform)) { console.warn('Unsupported platform:', platform); } return async (options) => { // 初始化配置 const config = { url: options.url, method: options.method || 'GET', header: options.header || {}, data: options.data || {}, timeout: options.timeout || 15000 }; try { // 请求拦截处理 const processedConfig = requestInterceptor(config); // 发起请求 const response = await new Promise((resolve, reject) => { uni.request({ ...processedConfig, success: resolve, fail: reject }); }); // 响应拦截处理 return responseInterceptor(response); } catch (error) { return errorHandler(error); } }; }; // 常用请求方法 const http = { get: (url, params, config = {}) => { return createRequest()({ url, method: 'GET', data: params, ...config }); }, post: (url, data, config = {}) => { return createRequest()({ url, method: 'POST', data, ...config }); }, put: (url, data, config = {}) => { return createRequest()({ url, method: 'PUT', data, ...config }); }, delete: (url, config = {}) => { return createRequest()({ url, method: 'DELETE', ...config }); }, // 下载文件方法 download: async (url) => { const platformConfig = getPlatformConfig(); // 添加token const token = uni.getStorageSync(platformConfig.storageKey); let header = {} header[platformConfig.authHeader]=`Bearer ${token}` // 处理URL const reqUrl = url if (!reqUrl.startsWith('http')) { reqUrl = `${platformConfig.baseURL}${config.url}`; } return new Promise((resolve, reject) => { uni.downloadFile({ reqUrl, header:header, success: (res) => { if (res.statusCode === 200) { resolve(res); } else { reject(new Error(`下载失败,状态码: ${res.statusCode}`)); } }, fail: reject }); }); } }; // 全局挂载 uni.$http = http; export default http;