const app = getApp(); const { baseUrl } = app.globalData; // 全局配置 请求拦截, 长时间 const buildRequest = (type, url, data) => { return new Promise((resolve, reject) => { if (url.indexOf('token') == -1) { let token = wx.getStorageSync('token'); if (token) { url += url.indexOf('?') == -1 ? '?' : '&'; url += `token=${token}`; } } if (url.indexOf('http') != 0) { url = baseUrl + url; } wx.request({ url, data, method: type, success: res => { if (res.statusCode == 200 || res.statusCode == 204) { resolve(res.data); return; } if (res.statusCode == 400) { console.error("400报错" + url, res); wx.showToast({ title: res.data.message, icon: "none", duration: 1500 }); // reject(res); } if (res.statusCode == 401) { wx.clearStorageSync(); wx.reLaunch({ url: '/pages/login/login' }); } }, fail: err => { wx.showToast({ title: '网络异常', icon: 'none', duration: 1500 }) console.error('网络异常' + url, err); reject(err); } }); }); } // 请求拦截 let Request = {}; Request.get = (url, query) => { return buildRequest('GET', url, query); } Request.post = (url, data) => { return buildRequest('POST', url, data); } Request.put = (url, data) => { return buildRequest('PUT', url, data); } Request.del = (url, data) => { return buildRequest('DELETE', url, data); } module.exports = { Request }