import Request from './request'; import apiList from './api.js' const shoproRequest = new Request(); export default function http(url, data = {}, toastBefore = '', // 请求前加载提示 toastAfter = true, // 请求后错误提示 ) { let api = getApiPath(url); /* 请求之前拦截器 */ shoproRequest.interceptor.request((config, cancel) => { let token = uni.getStorageSync('token') || ""; if (api.auth && !token) { uni.hideLoading(); uni.showToast({ title: '暂未登录,请先登录', icon: 'none', duration: 2000, }); uni.navigateTo({ url: '/pages/login/index', success: function(res) {} }); throw (`暂未登录,已阻止此次API请求: '${api.url}'`); } token && shoproRequest.setConfig(config => { config.header.Authorization = token }) if (toastBefore !== '') { uni.showLoading({ title: toastBefore, mask: true }); } return config }); /* 请求之后拦截器 */ shoproRequest.interceptor.response((response) => { uni.hideLoading(); if (response.statusCode !== 200 || response.data.success === false) { if (toastAfter) { if (response.statusCode === 401 || response.statusCode === 502 || response.data.code === 161099) { uni.showToast({ title: '请重新登录!', icon: 'none', duration: 1000, mask: true }); uni.redirectTo({ url: '/pages/login/index' }); } else { uni.showToast({ title: response.data.message || '请求出错,稍后重试', icon: 'none', duration: 1000, mask: true }); } } } return response.data }) return shoproRequest.request({ url: api.url || url, data, method: api.method }) } // 组装接口路径 function getApiPath(url) { let api; let apiArray = url.split("."); if (apiArray.length == 1) { api = { auth: true, method: "POST", url: url, } } else { api = apiList; apiArray.forEach(v => { api = api[v]; }); } return api; }