/** * 封装的异步请求处理函数 * 使用方法为: * request('接口名称',{key:value},'请求方式(默认为GET)') * .then(res=>{console.log(res)}) */ import {getToken} from "./auth"; import CONFIG from '@/config' export const baseUrl = CONFIG.apiUrl const whitePath = ['/pages/login/index1'] async function request(method, params, type = 'GET') { //创建一个名为request请求的方法函数 const token = getToken() // if (!token) { // uni.navigateTo({ // url:'/pages/login/index1' // }) // return // } let header = { //设置请求头信息 'X-Access-Token': token, 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" }; let http = { url: baseUrl + method, data: params, method: type.toUpperCase(), header: header }; return new Promise((resolve, reject) => { uni.request(http).then(res => { uni.hideLoading() let newData = res[1].data; // if (newdata.code == 403) { if (newData == -1) { //如果错误码为 -1 提示 uni.showToast({ title: res[1].data.msg, icon: 'none' }); } if (![200, 0].includes(newData.code)) { if (newData.code === 401) { uni.showToast({ title: newData.message, icon: 'none' }); uni.removeStorageSync('userinfo') uni.removeStorageSync('token') setTimeout(() => { uni.redirectTo({ url: '/pages/login/index1' }) }, 500) } else { uni.showToast({ title: newData.message, icon: 'none' }); } reject(newData); } resolve(newData); }).catch(err => { uni.hideLoading() if (err.statusCode === 401) { uni.redirectTo({ url: '/pages/login/index1?status=' + 1 }) } reject(err); console.log(err); }); }); } export default request