// 引入 import { Storage } from '@/service/storage' const storage = new Storage() // 引入跳转文件 import { Navigation } from '@/service/navigation' // 创建跳转实例 const navigation = new Navigation() let baseUrl = import.meta.env.VITE_APP_API_BASEURL let warning = true // 暴露封装方法 export function Request(params, loading = false) { // 判断是否还在请求,如果在就提示加载中 if (loading) { uni.showLoading({ mask: true, title: '加载中' }) } return new Promise((resolve, reject) => { const headers = { 'accessToken': storage.getStorageSync('accessToken'), ...params.headers // 外部传入的headers }; if(params.baseUrl) { baseUrl = params.baseUrl } uni.request({ ...params, url: baseUrl + params.url, method: params.method || 'GET', timeout: 40000, header: headers, success: (res) => { // console.log(res) if (res.statusCode === 200) { // 成功回调 switch (parseInt(res.data.code)) { case 11: uni.showToast({ title: res.data.message, icon: 'none' }) setTimeout(() => { if (res.data.message == '登录超时,请重新登录') { LogOut() } }, 1000) resolve(res.data) break; case 200: resolve(res.data) break; case 401: uni.showToast({ title: '您的账号已在其他设备登陆, 被迫下线', icon: 'none' }) setTimeout(() => { LogOut() }, 2000) break; case 151: toast(res) break; case 190: toast(res) setTimeout(() => { navigation.switchTab('/pages/index/index') }, 1000) break; case 112: uni.showToast({ icon: 'none', title: '存在已重复提交数据' }); break; case 404: uni.showToast({ icon: 'none', title: '资源不存在' }); break; case 500: resolve(res) break; case 1: if (!res.data.msg && !res.data.message) { resolve(res.data) return } if (res.data.message != '系统异常') { if (warning) { warning = false uni.showToast({ icon: 'none', title: res.data.msg || res.data.message, duration: 2000 }) setTimeout(() => { warning = true }, 2000) } } resolve(res.data) break; case 0: resolve(res.data) break; default: uni.showToast({ icon: 'none', title: res.data.msg || res.data.message, duration: 2000 }); } } else { statusCodeToast(res.statusCode) } }, fail: function(err) { // console.log(err) // storage.clearStorageSync() // LogOut() resolve(err) // uni.showToast({ // icon: 'none', // title: '请求服务器失败!', // duration: 2000 // }); }, complete: function() { if (loading) { uni.hideLoading() } } }); }) } // 封装方法跳转登录页 function LogOut() { storage.clearStorageSync() navigation.relaunch('/pages/login/login') } // 封装方法弹出提示 function toast(res) { uni.showToast({ icon: 'none', title: res.data.msg, duration: 2000 }); } // 封装方法根据错误码弹出提示 function statusCodeToast(code) { const statusMap = { '500': '服务器繁忙', '502': '服务器繁忙', '404': '资源不存在', } uni.showToast({ icon: 'none', title: statusMap[code], duration: 2000 }); }