123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865 |
- 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
- }
|