import coreRequest from './request' import apiList from './apis.js' import store from '@/core/store/index.js' import { setToken,removeToken } from '../utils/auth'; import router from '@/core/router' const Request = new coreRequest(); export default function http( url, data = {}, toastBefore = '', // 请求前加载提示 toastAfter = true, // 请求后错误提示 responseType = 'text' ) { let api = getApiPath(url); console.log(api); /* 请求之前拦截器 */ Request.interceptor.request((config, cancel) => { let token = uni.getStorageSync('token'); if (api.auth && !token) { store.dispatch('logout'); uni.hideLoading() throw (`暂未登录,已阻止此次API请求: '${api.url}'`); } token && Request.setConfig(config => { config.header.authorization = `Bearer ${token}` }) if (toastBefore !== '') { uni.showLoading({ title: toastBefore, mask: true }); } return config }); /* 请求之后拦截器 */ Request.interceptor.response((res) => { const headers = res.header; console.log(res); const response = res.data; const token = headers?.authorization || headers?.Authorization // 新的token if (token) { const newToken = token.substring(7) // 去掉'Bearer '前缀 setToken(newToken) } uni.hideLoading(); if (response?.flag === "failure") { if (toastAfter) { uni.showToast({ title: response.message || '请求出错,稍后重试', icon: 'none', duration: 1000, mask: true }); } } // token过期注销 if (res.statusCode === 401) { removeToken(); uni.showToast({ title: '登录已过期,请重新登录', icon: 'none', duration: 1000, mask: true }); uni.reLaunch('/pages/login/index') } return response }) return Request.request({ url: api.url, path: api.path, data, method: api.method, responseType }) } // 组装接口路径 function getApiPath(url) { let apiArray = url.split("."); let api = apiList; apiArray.forEach(v => { api = api[v]; }); return api; }