/** * 网络请求封装 */ // 固定的 clientid const CLIENT_ID = '2f847927afb2b3ebeefc870c13d623f2' // 基础 URL(根据实际情况修改) const BASE_URL = '' /** * 封装的请求方法 * @param {Object} options - 请求配置 * @param {String} options.url - 请求地址 * @param {String} options.method - 请求方法,默认 GET * @param {Object} options.data - 请求参数 * @param {Object} options.header - 额外的请求头 * @returns {Promise} */ const request = (options) => { return new Promise((resolve, reject) => { // 获取存储的 token const token = uni.getStorageSync('token') || '' uni.request({ url: BASE_URL + options.url, method: options.method || 'GET', data: options.data || {}, header: { 'Content-Type': 'application/json', 'clientid': CLIENT_ID, 'token': token, ...options.header }, success: (res) => { const { code, msg, data, total, rows } = res.data // 根据状态码处理 switch (code) { case 200: // 操作成功,返回数据 if (total !== undefined && rows !== undefined) { // 分页查询返回体 resolve({ total, rows, code, msg }) } else { // 一般返回体 resolve({ code, msg, data }) } break case 401: // token 失效 uni.showToast({ title: 'token失效,请重新登录', icon: 'none', duration: 2000 }) // 清除 token uni.removeStorageSync('token') // 跳转到登录页(如果有的话) // uni.navigateTo({ url: '/pages/login/login' }) reject({ code, msg: 'token失效' }) break case 500: // 系统错误 uni.showToast({ title: '系统错误', icon: 'none', duration: 2000 }) reject({ code, msg: '系统错误' }) break case 501: // 提示返回的 msg uni.showToast({ title: msg || '请求失败', icon: 'none', duration: 2000 }) reject({ code, msg }) break default: // 其他状态码 uni.showToast({ title: msg || '请求失败', icon: 'none', duration: 2000 }) reject({ code, msg }) break } }, fail: (err) => { uni.showToast({ title: '网络请求失败', icon: 'none', duration: 2000 }) reject(err) } }) }) } export default request