const app = getApp(); let loadingCount = 0; const showLoading = (title) => { if (loadingCount === 0) { wx.showLoading({ title: title, mask: true }); } loadingCount++; }; const hideLoading = () => { if (loadingCount > 0) { loadingCount--; } if (loadingCount === 0) { wx.hideLoading(); } } const ajax = (url, params, methos, loading = true, title = "加载中...", contentType = "application/json") => { let requestUrl = app.globalData.wxRequestUrl + url; if (loading) { showLoading(title); } return new Promise((resolve, reject) => { let header = { "content-type": contentType }; let token = wx.getStorageSync("token"); if (Boolean(token)) { header['X-Access-Token'] = token; } wx.request({ url: requestUrl, data: params, method: methos, header: header, success: (res) => { if (loading) { hideLoading(); } console.log("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 开始 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓"); switch (res.data.code) { case 200: resolve(res.data); console.log("接口【 " + url + " 】请求成功!状态码为:200(正常)"); break; case 400: reject(res.data); console.error("接口【 " + url + " 】请求错误!状态码为:400(报错)"); break; case 401: wx.clearStorageSync(); reject(res.data); console.error("接口【 " + url + " 】请求错误!状态码为:401(未登录)"); break; case 500: reject(res.data); console.error("接口【 " + url + " 】请求错误!状态码为:500(服务器错误)"); break; default: reject(res.data); console.error("接口【 " + url + " 】请求错误!状态码为:未知"); } console.log("Header参数为 ↓↓↓"); console.log(header); console.log("请求参数为 ↓↓↓"); console.log(params); console.log("返回参数为 ↓↓↓") console.log(res.data); console.log("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 结束 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑"); }, fail: (error) => { if (loading) { hideLoading(); } wx.showToast({ title: "请求失败,请重试!", icon: "none" }) reject(error); } }) }) } export default { ajax }