/* 请求的错误不应该被调用方被catch 把错误的请求当成请求正常返回的结果 由调用方根据状态码来判断是否成功 */ var base64 = require('/base64'); const app = getApp(); const config = require('../config/config.js'); const constants = require('../utils/Constants'); /* 服务端IP+端口 */ export const API_URI = (app && app.globalData && app.globalData.URI) ? app.globalData.URI : (config.server_add + ':' + config.server_port) /* 调用的请求方法 */ function request(url, requestType, params) { return new Promise((resolve, reject) => { wxRequest(url, requestType, params).then(res => { console.log('[请求地址]:', url, '\n[请求参数]:', params, '\n[响应状态]:', res.data.code, '\n[响应数据]:', res.data.data, '\n[响应信息]:', res.data.message, '\n[异常信息]:', res.data.exception) switch (res.data.code) { case 200: break; case 1015://1015 当前用户未注册 2022年11月14日 break; case -2: case -4: case 233: wx.showModal({ title: '提示', content: res.data.message, showCancel: false, success: function (res) { wx.navigateTo({ url: '/pages/login/login', }) } }); break; default: if (res.data.exception) { wx.showModal({ title: '提示', content: res.data.message, cancelText: '日志', success(res_model) { if (res_model.cancel) { wx.showModal({ title: '异常信息', content: res.data.exception, showCancel: false }); } } }); } else { wx.showModal({ title: '提示', content: res.data.message, showCancel: false }); } break; } resolve(res) }).catch(err => { resolve({ code: -200, message: "请求失败", data: err }); }) }) } /* 封装wx.request */ function wxRequest(url, requestType, params) { return new Promise((resolve, reject) => { let app = getApp(), header = { 'content-type': 'application/json' } var openId = app.globalData.openid if (app.globalData.user) { app.globalData.user.openId = openId // 请求的Authorization if(app.globalData.token){ header['Authorization'] = "Bearer " + app.globalData.token } } // 语言 header['i18n'] = constants.lan if (app && app.globalData && app.globalData.company && app.globalData.company.svcCode) { url = url.replace('mdm-server', 'mdm-server' + '-' + app.globalData.company.svcCode.replace('_', '-')) } wx.request({ url: `${API_URI}/${url}`, header: header, data: params ? params : null, method: requestType ? requestType : 'POST', success: function (res) { resolve(res); }, fail: function (err) { reject(err); } }) }) } /* 暴露方法给外部 */ module.exports = { request }