import { ACCESSTOKEN, config, DEBUG } from '@/common/config.js' import util from '@/common/util.js' function getToken() { let token = uni.getStorageSync("sessionToken") return util.isBlank(token) ? '' : token } module.exports = (vm) => { const url = config.serverUrl uni.$u.http.setConfig((config) => { config.baseURL = url config.header = { 'Accept': 'application/json, text/plain, */*', // 'Content-Type': 'application/x-www-form-urlencoded', } return config }); // 请求拦截,配置Token等参数 uni.$u.http.interceptors.request.use((config) => { // 引用token const TOKEN = getToken() || null; if (TOKEN) { config.header[ACCESSTOKEN] = TOKEN; } else { delete config.header[ACCESSTOKEN] } if (config.custom.loading) { uni.showLoading({ title: '加载中', mask: true }) } DEBUG && console.log('请求参数', config); return config; }, config => { // 可使用async await 做异步操作 return Promise.reject(config) }) // 响应拦截,判断状态码是否通过 uni.$u.http.interceptors.response.use((res) => { uni.hideLoading() DEBUG && console.log('返回结果', res); if(res.statusCode!=200){ vm.$u.toast(res.data?.msg || "请求异常!"); //错误提示信息 return false; } if (res.data.code == 200 || !res.data.code) { return res } else if (res.data.code == 10002) { return res } else if (res.data.code == 401) { const TOKEN = uni.getStorageSync("sessionToken") if (TOKEN) { // vm.$u.vuex('userInfo', null) // vm.$u.vuex('token', null) // uni.removeStorageSync("sessionToken") uni.clearStorageSync() // 清楚所有的缓存 uni.showToast({ title: '授权过期,请重新登录', icon: 'none', mask: true }) setTimeout(() => { uni.reLaunch({ url: '/pages/index/index' }) }, 900) } else { uni.showToast({ title: res.data?.msg || "请求异常!", icon: 'none', mask: true }) } return false; } else { vm.$u.toast(res.data.msg || "请求异常!"); //错误提示信息 return false; } }, (response) => { // 对响应错误做点什么 (statusCode !== 200) uni.hideLoading() if(response.config.custom?.loading) { uni.hideLoading() } return Promise.reject(response) }) }