import {baseUrl} from './config.js' import store from '@/store/index.js' import {apiWXLogin} from '@/api/user.js' // 请求错误消息提示 const showError=error=>{ let errMsg='' switch(error.code){ case 400: errMsg=error.msg; break; default: errMsg=error.msg; break; } uni.showToast({ title:errMsg, icon:'none', duration:1000 }) } // 刷新token 微信登录 const wechatLogin=()=>{ return new Promise((resolve,reject)=>{ uni.login({ provider: 'weixin', success: function (loginRes) { apiWXLogin({Code:loginRes.code}).then(res=>{ if(res.code===200){ store.commit('addToken', res.data.Authorization) store.commit('addUserData',res.data.UserInfo) resolve(res.data) } }) }, fail:function(loginErr){ uni.showToast({ title:"微信登录失败", icon:"none" }) } }) }) } let requestList=[]//存放token失效时请求队列 let isRefreshing=false//是否正在刷新token /** * 刷新token */ const refreshToken=async (url,params,method,resolve)=>{ requestList.push(()=>{resolve(http(url,params,method))}) if(!isRefreshing){ isRefreshing=true const wechatLoginRes=await wechatLogin() console.log(wechatLoginRes); // 重新请求队列 requestList.map(MT=>{MT()}) requestList=[] isRefreshing=false } } // 请求数 let LOADINGCOUNT = 0; const http=(url,params,method)=>{ // 设置loading if (LOADINGCOUNT === 0) { uni.showLoading({ title:'加载中...' }) } LOADINGCOUNT++; return new Promise((resolve,reject)=>{ uni.request({ url:baseUrl+url, data:params, method:method, header:{ Authorization:store.state.token, }, success(res) { if(![200,401,403].includes(res.data.code)){ setTimeout(()=>{showError(res.data)},0)//解决 hideloading 冲突问题 } //401 代表token异常,用户需要重新静默授权,获取最新的token //403 用户需要进行绑定操作,需要跳转到输入账号密码绑定页面用户需要进行绑定操作 if(res.data.code===401){ refreshToken(url,params,method,resolve) return } if(res.data.code===403){ uni.reLaunch({ url:"/pages/login/login" }) } resolve(res.data) }, fail(error) { console.log(error); setTimeout(() => { uni.showToast({ title:'网络异常', icon:'none' }) }, 0); }, complete() { // 关闭loading LOADINGCOUNT--; if (LOADINGCOUNT === 0) { uni.hideLoading() } } }) }) } // get 请求 export const httpGet=(url,params)=>{ return http(url,params,'GET') } // post 请求 export const httpPost=(url,params)=>{ return http(url,params,'POST') }