import Request from './luch-request/index.js'; // 基础的url // const baseUrl = 'https://xyb.hexieweb.cn/xyb100zz'; const baseUrl = 'http://192.168.1.168:5004'; const http = new Request({ baseURL: baseUrl, timeout: 10000 }) // 动态获取 token(从登录接口存储的) const getToken = () => { const token = uni.getStorageSync('token'); return token ? `Bearer ${token}` : ''; }; // 请求之前查看是否为空 const isEmptyObject = (obj) => { return Object.keys(obj).length === 0; }; // 将对象转换为查询字符串 const objectToQueryString = (obj) => { const keyValuePairs = []; for (let key in obj) { if (obj.hasOwnProperty(key)) { keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } } return keyValuePairs.join('&'); }; // 提示 function showToast(title) { uni.showToast({ title, icon: 'none', duration: 1000, }); } // 请求 const requestAPI = (config) => { // 支持对象参数或传统参数 let { url, method = 'GET', data = {}, noAuth = false } = typeof config === 'object' && config.url ? config : { url: config, method: arguments[1] || 'GET', data: arguments[2] || {} }; if (method == 'GET' && !isEmptyObject(data)) { url += '?' + objectToQueryString(data); } // 显示加载状态 uni.showLoading({ title: '加载中...' }); // 构建 header,登录等接口不需要 Authorization const header = { 'Content-Type': 'application/json' }; if (!noAuth) { const token = getToken(); if (token) { header['Authorization'] = token; } } return new Promise((resolve, reject) => { uni.request({ url: baseUrl + url, method, data, header, success: (res) => { uni.hideLoading(); // 检查HTTP状态码 if (res.statusCode !== 200) { console.error('HTTP错误:', res.statusCode); // showToast(`请求失败 ${res.statusCode}`); reject(`HTTP_${res.statusCode}`); return; } // 检查业务状态码(如果后端有的话) if (res.data && res.data.code !== undefined) { // 支持 code === 200 或 code === 0 作为成功状态 if (res.data.code === 200 || res.data.code === 0) { resolve(res.data); } else if (res.data.code === 401) { // token过期处理 uni.removeStorageSync('token'); uni.removeStorageSync('userInfo'); showToast('登录已过期,请重新登录'); setTimeout(() => { uni.reLaunch({ url: '/pages/login/login' }); }, 1500); reject('401'); } else { showToast(res.data.msg || '请求失败'); reject(res.data.code); } } else { // 没有业务状态码,直接返回数据 resolve(res.data); } }, fail: (err) => { console.error('网络请求失败:', err); uni.hideLoading(); // 区分不同的错误类型 if (err.errMsg && err.errMsg.includes('request:fail')) { showToast('网络连接失败,请检查网络设置'); } else if (err.errMsg && err.errMsg.includes('timeout')) { showToast('请求超时,请稍后重试'); } else { showToast('网络异常,请稍后重试'); } reject(err); } }); }); }; // 文件末尾应该导出 export { requestAPI, baseUrl, getToken };