const { host } = require('./env') /** * POST/GET/Put/Delete请求API */ function POST(options) { return request({ method: 'POST', ...options }) } function GET(options) { return request({ method: 'GET', ...options }) } function PUT(options) { return request({ method: 'PUT', ...options }) } function DEL(options) { return request({ method: 'DELETE', ...options }) } /** * 请求API * @param {String} url 接口地址 * @param {Object} params 请求的参数 * @param {String} method 请求类型 * @param {Object} page 来源页面对象 * @param {boolean} successFun 回调函数是否自定义 默认false,实用默认成功回调 * @param {boolean} failFun 回调函数是否自定义 默认false,实用默认成功回调 * @param {Function} onStartFun 接口开始之前的回调函数 * @param {Function} completeFun 接口调用结束的回调函数(调用成功、失败都会执行) * @param {String} contentType 请求header content-type的类型,只在无人酒店项目需要,其他项目可删除 * @param {boolean} isToken 是否需要token * @param {String} isLoadingTxt 是否有加载动画 * @param {String} successTxt 无成功回调函数,请求成功后的默认提示信息文字 * @param {boolean} isSubmitting 表单提交的状态,表单页面需要设置为true */ function request({ url, params = {}, method = 'GET', page, successFun = false, failFun = false, onStartFun, completeFun, contentType, isToken = true, isBearer = '',//token是否添加Bearer 前缀 Bearer 默认设置不加 isLoadingTxt = '加载中...', successTxt = '', isSubmitting = false }) { //需要测试 if (isSubmitting && page.data.isSubmitting){ console.log('不可重复提交') return; } if (isSubmitting){ page.setData({ 'isSubmitting': true }) } if (onStartFun) { onStartFun(); //request start } else { if (method == 'PUT' || method == 'POST' || method == 'GET') { if (isLoadingTxt) { wx.showLoading({ title: isLoadingTxt, mask: true }) } } else if (method == 'DELETE') { wx.showLoading({ title: '正在删除...', mask: true }) } } let myHeader = { 'content-type': contentType ? contentType : 'application/json', 'Token': wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : '' }; //通过includes方法查找字符串中是否包含指定内容,进而判断是否要添加token if (!isToken) { delete myHeader.Token } return new Promise((resolve, reject) => { wx.request({ url: host.BASE_URL + url, method: method, data: params, header: myHeader, success: function (res) { if (isLoadingTxt) wx.hideLoading(); if (res.data.code == '0' || res.data.code == '200' || res.data.code == '0000') { if (successFun) { resolve(res) } else { if(!successTxt){ switch (method) { case 'PUT': return successTxt = '修改成功' break; case 'POST': return successTxt = '新增成功' break; case 'DELETE': return successTxt = '删除成功' break; case 'GET': return successTxt = '查询成功' break; } } wx.showToast({ title: successTxt, icon: 'success', duration: 2000, mask: true }) } } else if (res.data.code == '401') { if (failFun) { reject(res) } else { wx.clearStorageSync() page.setData({ loginStatus: '' }) page.onShow() wx.showToast({ title: '登录已过期', icon: 'none', duration: 2000, mask: true, success: function () { setTimeout(function () { wx.navigateTo({ url: '/pages/login/index', }) }, 2000) } }) } } else { if (failFun) { reject(res) } else { wx.showToast({ title: res.data.msg ? res.data.msg : res.data.message ? res.data.message : '请求出错了,稍后再试!', icon: 'none', duration: 2000, mask: true }) } } //部分地磅会返回报错会返回html页面 let getDataStr = res.data if(typeof getDataStr === 'string' && getDataStr.indexOf('DOCTYPE html'==-1)){ wx.clearStorageSync() sourceObj.setData({ loginStatus: '' }) sourceObj.onShow() wx.showToast({ title: '登录已过期', icon: 'none', duration: 2000, mask: true, success:function(){ setTimeout(function(){ // wx.switchTab({ // url: '/pages/index/index', // }) },2000) } }) } }, fail: function (res) { wx.clearStorageSync() page.onShow() if (isLoadingTxt) wx.hideLoading(); if (failFun) { reject(res) } else { let content = '糟糕!网络奔溃了!刷新试试' if (res.errMsg === 'request:fail timeout') { content = '请求超时!再试一次' } if (page && page.data.showModal != true) { page.setData({ showModal: true }) wx.showModal({ title: '提示!', content: content, showCancel: false, mask: true, success: function (res) { if (res.confirm) { page.setData({ showModal: false }) page.onLoad(); page.onShow(); } else if (res.cancel) { page.setData({ showModal: false }) } } }) } } }, complete: function (res) { if (isSubmitting) page.setData({ 'isSubmitting': false }) if (completeFun) { typeof completeFun == 'function' && completeFun(res, page); } } }) }) } /** * GET请求数据列表API 初始化加载第一页数据 * @param {String} url 接口地址 * @param {Object} data 请求的参数 * @param {Object} page 来源对象this * @param {boolean} loadType 加载类型(滑动加载【true】&初始化加载【false】) * @param {Array} Array 数据存放位置 * @param {String} pageSize 每页数量字段名 * @param {String} pageNo 设置当前页码字段名 * @param {String} totalPage 设置总页数字段名 * @param {String} more 设置加载动画状态字段名 * @param {String} nomore 设置加载状态显示文字字段名 * @param {boolean} successFun 接口调用成功返回的回调函数,可用于处理数据,格式化数据 * @param {boolean} failFun 接口调用失败的回调函数 * @param {Function} completeFun 接口调用结束的回调函数(调用成功、失败都会执行) * @param {String} requestStatu 请求状态,为空时表示加载完成,为加载中等字样时表示处于加载中 * @param {String} isLoadingTxt 请求时的加载文字提示 */ function pageFirst({ url, params, page, requireType = 'GET', loadType = false, Array = 'resData', pageSize = 'limit', pageNo = 'page', totalPages = 'totalPages', more = 'more', nomore = 'nomore', requestStatu = 'requestStatu', isLoadingTxt = '加载中...', successFun = false, failFun = false, isToken = true, isBearer = '',//token是否添加Bearer 前缀 Bearer 默认设置不加 completeFun }) { wx.showNavigationBarLoading(); if (page.data[requestStatu]) { wx.showLoading({ title: isLoadingTxt, mask: true }) } let myHeader = { //'content-type': contentType ? contentType : 'application/json', 'Token': wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : '' }; //通过includes方法查找字符串中是否包含指定内容,进而判断是否要添加token if (!isToken) { delete myHeader.Token } return new Promise((resolve, reject) => { wx.request({ url: host.BASE_URL + url, method: requireType, data: params, header: myHeader, success: function (res) { if (page.data[requestStatu]) { wx.hideLoading() } if (res.statusCode == '200') { if (res.data.code == '0000' || res.data.code == '20' || res.data.code == '0' || res.data.code == '200') { page.setData({ showModal: false }) var data = []; if (successFun) { data = resolve(res); //console.log('Data:', data); // 处理成功返回的数据 } else { data = res.data.data.records; } if (loadType) { //滑动加载时 page.setData({ [Array]: page.data[Array].concat(data), [more]: true }) } else { //初始化加载 page.setData({ [Array]: data, //requestStatu: '' }) if (!(typeof successFun == 'function')) { page.setData({ [requestStatu]: '' }) } if (totalPages) { page.setData({ [totalPages]: Math.ceil(res.data.data.total / page.data[pageSize]) }) } } if(url=='/biz/record/page'&&page.data.activeIndex=='1'){ page.setData({ sendRecordNum:res.data.data.total }) } //当结果只有一页时,并且小于5条时 var getTotalRows = 0; getTotalRows = res.data.data.total; if (getTotalRows < page.data[pageSize] && getTotalRows > 3) { page.setData({ [nomore]: '没有更多数据了!', [more]: false }) } else if (getTotalRows < 3) { page.setData({ [nomore]: '', [more]: false }) } else { page.setData({ [nomore]: '' }) } } else if (res.data.code == '401') { wx.clearStorageSync() page.setData({ loginStatus: '' }) page.onShow() wx.showToast({ title: '登录已过期', icon: 'none', duration: 2000, mask: true, success: function () { setTimeout(function () { wx.navigateTo({ url: '/pages/login/index', }) }, 2000) } }) if (!loadType) { wx.hideLoading() } } else { wx.clearStorageSync() page.onShow() if (failFun) { reject(res) } else { wx.showToast({ title: res.data.msg ? res.data.msg : res.data.message ? res.data.message : '出错了', icon: 'none', duration: 2000, mask: true }) } if (!loadType) { wx.hideLoading() } } //部分地磅会返回报错会返回html页面 let getDataStr = res.data if(typeof getDataStr === 'string' && getDataStr.indexOf('DOCTYPE html'==-1)){ wx.clearStorageSync() sourceObj.setData({ loginStatus: '' }) sourceObj.onShow() wx.showToast({ title: '登录已过期', icon: 'none', duration: 2000, mask: true, success:function(){ setTimeout(function(){ // wx.switchTab({ // url: '/pages/index/index', // }) },2000) } }) } } else if (res.statusCode == '302' || res.statusCode == '400' || res.statusCode == '404') { wx.clearStorageSync() page.setData({ loginStatus: '' }) page.onShow() wx.showToast({ title: '登录已过期', icon: 'none', duration: 2000, mask: true, success: function () { setTimeout(function () { // wx.switchTab({ // url: '/pages/index/index', // }) wx.navigateTo({ url: '/pages/login/index', }) }, 2000) } }) if (!loadType) { wx.hideLoading() } } else { if (failFun) { reject(res) } else { wx.showToast({ title: res.data.msg ? res.data.msg : res.data.message ? res.data.message : '出错了,请稍后再试', icon: 'none', duration: 2000, mask: true }) if (page.onShow) { page.onShow() } } } }, fail: function (res) { wx.clearStorageSync() page.onShow() if (page.data[requestStatu]) { wx.hideLoading() } if (failFun) { reject(res) } else { let content = '糟糕!网络奔溃了!刷新试试' if (res.errMsg === 'request:fail timeout') { content = '请求超时!再试一次' } if (page.data.showModal != true) { page.setData({ showModal: true }) wx.showModal({ title: '提示!', content: content, showCancel: false, mask: true, success: function (res) { if (res.confirm) { page.setData({ showModal: false }) //page.onLoad(); } else if (res.cancel) { page.setData({ showModal: false }) } } }) } } }, complete: function (res) { wx.hideNavigationBarLoading(); // if(!loadType){wx.hideLoading()} if (completeFun) { typeof completeFun == 'function' && completeFun(res, page); } wx.stopPullDownRefresh(); if (loadType) { //数据加载完成后隐藏加载动画 page.setData({ [more]: false }) } } }) }) } /** * GET滑动请求数据列表API 触底加载 * @param {Object} page 来源对象this * @param {String} pageNo 设置当前页码字段名 * @param {String} totalPage 设置总页数字段名 * @param {String} more 设置加载动画状态 * @param {boolean} totalPages 设置总页数字段 */ function pageOther(options) { let { page, pageNo = 'page', totalPages = 'totalPages', more = 'more', nomore = 'nomore' } = options if (page.data[pageNo] > page.data[totalPages]) { //当前页大于总页数 page.setData({ [more]: false, [nomore]: '没有更多数据了!' }) return; } else { if (page.data[pageNo] >= page.data[totalPages]) { page.setData({ [nomore]: '没有更多数据了!' }) } page.setData({ [more]: true }) return pageFirst({ ...options }); } } /** * GET请求数据列表API 不带分页的请求全部数据 * @param {String} url 接口地址 * @param {Object} data 请求的参数 * @param {Object} header 请求的头 * @param {Object} page 来源对象this * @param {String} Array 数据存放位置 * @param {Boolean} successFun 接口调用成功返回的回调函数 * @param {Boolean} failFun 接口调用失败的回调函数 * @param {Function} completeFun 接口调用结束的回调函数(调用成功、失败都会执行) */ function pageAll({ url, data, page, Array, requestStatu, successFun, failFun, completeFun }) { if (page.data[requestStatu]) { wx.showLoading({ title: '加载中...', mask: true }) } return new Promise((resolve, reject) => { wx.request({ url: host.BASE_URL + url, method: 'GET', data: data, header: { //'content-type': 'application/json', // 默认值 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', 'Token': wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : '' }, success: function (res) { if (page.data[requestStatu]) wx.hideLoading(); if (res.statusCode == '200') { if (res.data.code == '0' || res.data.code == '200' || res.data.code == '0000') { page.setData({ showModal: false }) var data = []; if (successFun) { data = resolve(res); } else { data = res.data.data.records; } page.setData({ [Array]: data, more: false, nomore: '没有更多数据了!' }) if (!(typeof successFun == 'function')) { page.setData({ [requestStatu]: '' }) } } else if (res.data.code == '401') { if (failFun) { reject(res) } else { wx.clearStorageSync() page.setData({ loginStatus: '' }) page.onShow() wx.showToast({ title: '登录已过期', icon: 'none', duration: 2000, mask: true, success: function () { setTimeout(function () { // wx.switchTab({ // url: '/pages/index/index', // }) wx.navigateTo({ url: '/pages/login/index', }) }, 2000) } }) } } else { if (failFun) { reject(res) } else { wx.showToast({ title: res.data.msg ? res.data.msg : res.data.message ? res.data.message : '请求出错了,稍后再试!', icon: 'none', duration: 2000, mask: true }) } } } else { if (failFun) { reject(res) } else { wx.showToast({ title: res.data.msg ? res.data.msg : res.data.message ? res.data.message : '出错了,请稍后再试', icon: 'none', duration: 2000, mask: true }) if (page.onShow) { page.onShow() } } } }, fail: function (res) { if (page.data[requestStatu]) wx.hideLoading(); if (failFun) { reject(res) } else { let content = '糟糕!网络奔溃了!刷新试试' if (res.errMsg === 'request:fail timeout') { content = '请求超时!再试一次' } if (page.data.showModal != true) { page.setData({ showModal: true }) wx.showModal({ title: '提示!', content: content, showCancel: false, mask: true, success: function (res) { if (res.confirm) { page.setData({ showModal: false }) page.onLoad(); } else if (res.cancel) { page.setData({ showModal: false }) } } }) } } }, complete: function (res) { if (completeFun) { typeof completeFun == 'function' && completeFun(res, page); } } }) }) } /** * 单张图片上传 * seturl 设置URL * setfiled 字段名 * data 设置data数据 * refresh 上传完成后是否刷新 * 最终返回res */ function uploadPhoto(that, seturl, setfiled, data, refresh) { wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 wx.uploadFile({ url: seturl, filePath: res.tempFilePaths[0], name: setfiled, dataType: 'json', header: { 'content-type': 'application/json', // 默认值 'Token': wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : '' }, formData: data, success: function (res) { wx.hideLoading(); var data = res.data if (refresh) { that.onLoad(); } }, complete: function (res) { // app.globalData.loginCheck(e.data.code, e.data.desc); return res } }) } }) } /** * 多图片上传 * seturl 设置URL * setfiled 字段名 * data 设置data数据 */ function uploadMorePhoto(seturl, that, setfiled, data, successFun) { wx.chooseImage({ count: 9, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { var successUp = 0; //成功个数 var failUp = 0; //失败个数 var length = res.tempFilePaths.length; //总共个数 var i = 0; //第几个 /** * seturl 设置URL * res.tempFilePaths 所有土图片路径 * setfiled 字段名 * data 设置data数据 * successUp 上传成功的的数量 * failUp 上传失败的数量 * i 当前的索引 * length 上传的总数 */ uploadDIY(seturl, that, res.tempFilePaths, setfiled, data, successUp, failUp, i, length, successFun); } }) } /** * vant组件的图片上传 * @param {*} url * @param {*} page * @param {*} filePaths * @param {*} setfiled * @param {*} params * @param {*} successUp * @param {*} failUp * @param {*} i * @param {*} length * @param {*} successFun //是否重新自定义回调函数 */ function uploadDIY({ url, page, filePaths, setfiled = "file", params = {}, successUp = 0, failUp = 0, i = 0, length }) { return new Promise((resolve, reject) => { wx.uploadFile({ url: host.BASE_URL + url, filePath: filePaths, name: setfiled, formData: params, header: { 'content-type': 'application/json', // 默认值 'Token': wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : '' }, success: (res) => { successUp++; if (i == length) { wx.showToast({ title: '上传成功!', icon: 'success', duration: 2000 }) } resolve(res) }, fail: (err) => { failUp++; reject(err) }, complete: (res) => { i++; if (i == length) { //console.log('总共' + i +'张' + successUp + '张上传成功,' + failUp + '张上传失败!'); } else { //递归调用uploadDIY函数 //uploadDIY(url, page, filePaths, setfiled, data, successUp, failUp, i, length, successFun); } }, }); }) } module.exports = { POST, GET, PUT, DEL, pageFirst, pageOther, pageAll, uploadPhoto, //单图片上传 uploadMorePhoto, //多图片上传 uploadDIY }