import env from './env.js' import Vue from 'vue' import auth from './auth.js' function service(options = {}) { options.url = `${env.baseUrl}${options.url}`; //判断本地是否带有token,如果带有,则添加到请求中 const token =uni.getStorageSync("token") if (token) { options.header = { "content-type": "application/json", "Authorization": "Bearer " + token } } return new Promise((resolve, reject) => { options.success = (res) => { //如果返回的状态码不是200,则执行以下操作 if (res.statusCode !== 200) { uni.showToast({ icon: 'none', duration: 3000, title: `${res.errMsg}` }); //403错误需要重新登录 if (res.statusCode === 403) { auth.removeToken() uni.reLaunch({ url: "/pages/login/login.vue" }) } //返回错误信息 reject(res) } else { const code = res.data.code if (code === 1011006 || code === 1011007 || code === 1011008 || code === 1011009) { uni.showToast({ icon: 'none', mask: true, duration: 3000, title: `${res.data.message},需要重新登录`, success() { auth.removeToken() uni.reLaunch({ url: "/pages/login/login.vue" }) } }) } else if (code !== 200) { uni.showToast({ icon: 'none', duration: 3000, title: `${res.data.message}` }) } resolve(res) } }; options.fail = (res) => { uni.showToast({ icon: 'none', duration: 3000, title: '服务器错误,请稍后在试' }) reject(res) } uni.request(options) }) } export default service