/** * http事件委托 * * udData 说明 * udData.noloading 不需要请求 * udData.fullData 使用 reponse 返回的对象进行 success 回调 (jun_http.js) * udData.nodomain 仅限于web端使用,不适用 baseUrl 前置(即当前网址根路径) (jun_http.js) * udData.nokey 不需要mpToken参数 */ import Login from './jun_login' // import { MessageBox, Message, Loading } from 'element-ui' import fn from './fn' import xioFn from '../utils/xio_fn.js' import resStatusCode from './jun_httpStatus' // 过滤 html function filterHtml(str) { if (typeof str !== 'string') { return str } return str.replace(/\n|\t|\s/g, '').replace(/<\/script>/g, '').replace(/<[^>]+>/g, '') } // 对象转url参数 function urlEncode(param, key, encode) { if (param == null) return '' var paramStr = '' var t = typeof (param) if (t === 'string' || t === 'number' || t === 'boolean') { paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param) } else { for (var i in param) { var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i) paramStr += urlEncode(param[i], k, encode) } }screenLeft return paramStr } /** * 使用 element-ui loading service */ // let loadingInstance // 定义loading变量 // // 开始loading // function startLoading(){ // loadingInstance = Loading.service({ // lock: true, // text: '加载中...', // background: 'rgba(255,255,255,0.7)', // fullscreen: true, // }) // } // // 结束loading // function endLoading(){ // loadingInstance && loadingInstance.close() // } // 开始loading function startLoading(__request_option) { // console.log(request_option.udData) // request_option.udData && typeof request_option.udData.loading === 'function' && request_option.udData.loading() typeof window.appLoading === 'function' && window.appLoading() } // 结束loading function endLoading(_request_option) { // request_option.udData && typeof request_option.udData.hideLoading === 'function' && request_option.udData.hideLoading() typeof window.appHideLoading === 'function' && window.appHideLoading() } // 请求前处理参数 - get function getChangeRequestOption(get_option) { get_option = xioFn.httpOptionMd5Handle(get_option) if (!get_option.udData || !get_option.udData.nokey) { if (!get_option.params) { get_option.params = {} } // 补充参数 // 需要 we_session var we_session = fn.getLocalStorage('we_session') if (we_session && we_session.we_session) { get_option.params.key = we_session.we_session get_option.params.mpToken = we_session.we_session } } return get_option } // 请求前处理参数 - post function postChangeRequestOption(post_option) { // console.log('============================>', post_option) // adminToken // var adminToken = fn.getSessionStorage('adminToken') // var urlEncodes = {} // if (adminToken && (!post_option.udData || !post_option.udData.nokey)) { // urlEncodes = { adminToken: adminToken, mpToken: adminToken } // } // // // 将请求参数放到链接后面 // var paramsUrl = urlEncode(urlEncodes) // if (!/\?/.test(post_option.url)) { // paramsUrl = paramsUrl.replace('&', '?') // } // post_option.url = post_option.url + paramsUrl // 请求头md5处理 post_option = xioFn.httpOptionMd5Handle(post_option) if (!post_option.udData || !post_option.udData.nokey) { if (!post_option.data) { post_option.data = {} } // 补充参数 // 需要 we_session var we_session = fn.getLocalStorage('we_session') if (we_session && we_session.we_session) { post_option.data.key = we_session.we_session post_option.data.mpToken = we_session.we_session } } return post_option } var httpEventCode = { code200() { // console.log(data, 200) }, code404(_url) { // element-ui // Message.error('无法访问接口,状态404:' + url) }, code500(_data, __url) { // element-ui // Message.error('请求失败,状态500:' + url) } } var g_login_counter = 0 // 登录请求次数 const g_LOGIN_MAX = 10 // 最大请求次数 var g_flag_loading = false // 是否已经loading var g_flag_login_requested = false // 是否正在请求登录 var g_login_result = null // 登录返回数据 var g_flag_config_requested = false // 其余配置请求 var g_config_result = null // 配置请求返回 // 请求前 function beforeRequest(res) { // 开启loading if (!g_flag_loading && (!res.request_option.udData || !res.request_option.udData.noLoading)) { res.http_option.debug && console.log('jun_httpEvent beforeRequest loading') // wx.showLoading({ // title: '加载中', // mask: true // }) // loading startLoading(res.request_option) g_flag_loading = true } // 重置登录请求标记 var we_session = fn.getLocalStorage('we_session') if (we_session && we_session.we_session) { g_flag_login_requested = false } } // 请求后 function afterRequest(_res) { // console.log('请求后') } // 处理返回数据 // @return {Object} 处理过的数据 function successChangeData(res) { return res } // 批量请求完成 function afterMultiRequests(request_option) { // console.log("多个请求结束之后") // 关闭loading if (g_flag_loading) { // wx.hideLoading() endLoading(request_option) g_flag_loading = false } } function updateKey(res, key) { // 更新 key 值 if (res.request_option.method === 'GET' && (!res.request_option.udData || !res.request_option.udData.nokey)) { res.request_option.url = res.request_option.url.replace(/mpToken=[^&]*/g, `mpToken=${key}`) } if (res.request_option.method === 'POST' && (!res.request_option.udData || !res.request_option.udData.nokey)) { res.request_option.data.mpToken = key } return res } // 模拟数据处理流程 function mockFlow(res) { return new Promise(async(resolve, _reject) => { // 打印请求信息 res.http_option.debug && console.log('模拟请求', res.request_option) var mockData = res.request_option.mockData || { code: 100, data: {}, message: 'success' } // 打印返回信息 res.http_option.debug && console.log('模拟返回', { data: mockData }) res.http_option.debug && console.log('开始模拟等待800ms') var timer = setTimeout(() => { clearTimeout(timer) // 关闭loading if (g_flag_loading) { // wx.hideLoading() endLoading(res.request_option) g_flag_loading = false } res.http_option.debug && console.log('结束模拟等待800ms') if (res.request_option.udData && res.request_option.fullData) { resolve({ data: mockData }) } else { resolve(mockData) } }, 800) }) } // 请求前处理流程 function beforeFlow(res) { return new Promise(async(resolve) => { // 预留请求前处理 // 设置为true,下次处理跳过 beforeFlow,避免死循环 res.request_option.skip_before_flow = true // 再次请求 resolve(res.Request(res.request_option)) }) } // 预留其余处理 function configRequest() { return new Promise((resolve, reject) => { resolve({}) }) } // 登录处理 function appLogin(option = {}) { return new Promise((resolve, reject) => { // Login.checkLogin({ // force: !!option.forceLogin, // callback: (key)=>{ // resolve(key) // } // }) Login.toLongUrl() }) } // 请求后处理 function afterFlow(res) { return new Promise((resolve, reject) => { var data = res.res.data // console.log('0000000000000000000', res) // 登录超时 if ( (data && data.res && data.res.status == 2) || (data && data.code == 603) ) { res.http_option.debug && console.log('登录超时,需要重新登录', res.res) // 登录超时,需要重新登录 // 清空we_session // getApp().globalData.we_session = null // fn.removeLocalStorage('we_session') // resolve(retryLogin(res)) // todo // // 清空登录凭证和用户数据 // sessionStorage.clear() // // 未登录,跳转登录页面 // this.$router.replace({ path: '/login' }) return } // status不为0 if ( (data && data.res && data.res.status != 0) || (data && data.code != 100) ) { if (data.res) { console.error('status不为0:' + (res.res.errMsg || ''), res.res) // 弹出提示 // wx.showModal({ // title: '请求提示', // content: data.res.errMsg || `请求有误,status=${data.res.status}`, // confirmText: '确定', // confirmColor: '#576B95', // showCancel: false // }) // element-ui // Message.error(data.res.errMsg || `请求有误,status=${data.res.status}`) // 根据status处理 if (typeof resStatusCode['status' + data.res.status] === 'function') { resStatusCode['status' + data.res.status](data) } } if (typeof data.code !== 'undefined') { console.error('code不为100:' + data.code, data.msg, res.res) } reject(res.res) return } // status为空 if (data && !data.res && typeof data.code === 'undefined') { console.error('status为空', res.res) let tips = '' if (res.res.statusCode == '500') { tips = '当前网络状态不佳,请稍后再试:statusCode=500;' } else if (res.res.statusCode == '200') { if (typeof res.data === 'string') { tips = filterHtml(res.data) } if (typeof res.data === 'object') { tips = filterHtml(JSON.stringify(res.data)) } tips = '网络状况不佳,点击确定重试:statusCode=200;' + tips } else { tips = `连接服务器失败,点击确定重试:statusCode=${res.res.statusCode};` } // 请求提示 // 小程序 // wx.showModal({ // title: '请求提示', // content: tips, // confirmText: '确定', // confirmColor: '#576B95', // showCancel: false, // success (res) { // if (res.confirm) { // // 点击确认后重新请求 // resolve(res.Request(res.request_option)) // } // } // }) // element-ui // MessageBox.alert(tips, '网络提示', { // confirmButtonText: '确定', // type: 'error' // }).then(()=>{ // resolve(res.Request(res.request_option)) // }).catch(()=>{ // // 点击取消 // }) return } // 打印返回信息 res.http_option.debug && console.log('返回', res.res) if (res.request_option.udData) { // 返回全部数据 if (res.request_option.udData.fullData === true) { resolve(res.res) } } g_login_counter && (g_login_counter = 0) resolve(data) }) } // 重新登录 async function retryLogin(res) { // 次数+1 g_login_counter++ return new Promise(async(resolve, _reject) => { // 等待登录 var login_result = await appLogin({ forceLogin: true }) // 登录失败 if (!login_result && g_login_counter < g_LOGIN_MAX) { // 2秒后重试 var timer = setTimeout(() => { clearTimeout(timer) resolve(retryLogin(res)) }, 2000) } // 登录成功 if (login_result) { // 更新key值 res = updateKey(res, login_result) // 再次请求 resolve(res.Request(res.request_option)) } }) } export default { httpEventCode, getChangeRequestOption, postChangeRequestOption, successChangeData, beforeRequest, afterRequest, afterMultiRequests, mockFlow, beforeFlow, afterFlow }