long
2024-06-26 911e0ed72a790ba054385ffe594262e123948691
提交 | 用户 | age
3ac5f2 1 /**
J 2  * http事件委托
6da3c1 3  *
3ac5f2 4  * udData 说明
J 5  * udData.noloading 不需要请求
6  * udData.fullData 使用 reponse 返回的对象进行 success 回调 (jun_http.js)
7  * udData.nodomain 仅限于web端使用,不适用 baseUrl 前置(即当前网址根路径) (jun_http.js)
8  * udData.nokey 不需要mpToken参数
9  */
10
11 import Login from './jun_login'
12 // import { MessageBox, Message, Loading } from 'element-ui'
13 import fn from './fn'
6da3c1 14 import xioFn from '../utils/xio_fn.js'
3ac5f2 15 import resStatusCode from './jun_httpStatus'
J 16 // 过滤 html
6da3c1 17 function filterHtml(str) {
J 18   if (typeof str !== 'string') {
19     return str
20   }
21   return str.replace(/\n|\t|\s/g, '').replace(/<script\s?.+><\/script>/g, '').replace(/<[^>]+>/g, '')
22 }
23 // 对象转url参数
24 function urlEncode(param, key, encode) {
25   if (param == null) return ''
26   var paramStr = ''
27   var t = typeof (param)
28   if (t === 'string' || t === 'number' || t === 'boolean') {
29     paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param)
30   } else {
31     for (var i in param) {
32       var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
33       paramStr += urlEncode(param[i], k, encode)
3ac5f2 34     }
6da3c1 35   }screenLeft
J 36   return paramStr
3ac5f2 37 }
J 38
39 /**
40  * 使用 element-ui loading service
41  */
42 // let loadingInstance // 定义loading变量
43 // // 开始loading
44 // function startLoading(){
45 //     loadingInstance = Loading.service({
46 //         lock: true,
47 //         text: '加载中...',
48 //         background: 'rgba(255,255,255,0.7)',
49 //         fullscreen: true,
50 //     })
51 // }
52 // // 结束loading
53 // function endLoading(){
54 //     loadingInstance && loadingInstance.close()
55 // }
56
57 // 开始loading
6da3c1 58 function startLoading(__request_option) {
J 59   // console.log(request_option.udData)
60   // request_option.udData && typeof request_option.udData.loading === 'function' && request_option.udData.loading()
61   typeof window.appLoading === 'function' && window.appLoading()
3ac5f2 62 }
J 63
64 // 结束loading
6da3c1 65 function endLoading(_request_option) {
J 66   // request_option.udData && typeof request_option.udData.hideLoading === 'function' && request_option.udData.hideLoading()
67   typeof window.appHideLoading === 'function' && window.appHideLoading()
3ac5f2 68 }
J 69
70 // 请求前处理参数 - get
6da3c1 71 function getChangeRequestOption(get_option) {
J 72   get_option = xioFn.httpOptionMd5Handle(get_option)
73   if (!get_option.udData || !get_option.udData.nokey) {
74     if (!get_option.params) {
75       get_option.params = {}
76     }
77     // 补充参数
78     // 需要 we_session
79     var we_session = fn.getLocalStorage('we_session')
80     if (we_session && we_session.we_session) {
81       get_option.params.key = we_session.we_session
82       get_option.params.mpToken = we_session.we_session
83     }
84   }
85   return get_option
3ac5f2 86 }
J 87 // 请求前处理参数 - post
6da3c1 88 function postChangeRequestOption(post_option) {
J 89   // console.log('============================>', post_option)
90   // adminToken
91   // var adminToken = fn.getSessionStorage('adminToken')
92   // var urlEncodes = {}
93   // if (adminToken && (!post_option.udData || !post_option.udData.nokey)) {
94   //   urlEncodes = { adminToken: adminToken, mpToken: adminToken }
95   // }
96   // // // 将请求参数放到链接后面
97   // var paramsUrl = urlEncode(urlEncodes)
98   // if (!/\?/.test(post_option.url)) {
99   //   paramsUrl = paramsUrl.replace('&', '?')
100   // }
101   // post_option.url = post_option.url + paramsUrl
102   
103   // 请求头md5处理
104   post_option = xioFn.httpOptionMd5Handle(post_option)
105   if (!post_option.udData || !post_option.udData.nokey) {
106     if (!post_option.data) {
107       post_option.data = {}
108     }
109     // 补充参数
110     // 需要 we_session
111     var we_session = fn.getLocalStorage('we_session')
112     if (we_session && we_session.we_session) {
113       post_option.data.key = we_session.we_session
114       post_option.data.mpToken = we_session.we_session
115     }
116   }
117   return post_option
3ac5f2 118 }
J 119
120 var httpEventCode = {
6da3c1 121   code200() {
J 122     // console.log(data, 200)
123   },
124   code404(_url) {
125     // element-ui
126     // Message.error('无法访问接口,状态404:' + url)
127   },
128   code500(_data, __url) {
129     // element-ui
130     // Message.error('请求失败,状态500:' + url)
131   }
3ac5f2 132 }
J 133
134 var g_login_counter = 0 // 登录请求次数
135 const g_LOGIN_MAX = 10 // 最大请求次数
136
137 var g_flag_loading = false // 是否已经loading
138 var g_flag_login_requested = false // 是否正在请求登录
139 var g_login_result = null // 登录返回数据
140 var g_flag_config_requested = false // 其余配置请求
141 var g_config_result = null // 配置请求返回
142 // 请求前
6da3c1 143 function beforeRequest(res) {
J 144   // 开启loading
145   if (!g_flag_loading && (!res.request_option.udData || !res.request_option.udData.noLoading)) {
146     res.http_option.debug && console.log('jun_httpEvent beforeRequest loading')
147     // wx.showLoading({
148     //     title: '加载中',
149     //     mask: true
150     // })
151     // loading
152     startLoading(res.request_option)
153     g_flag_loading = true
154   }
3ac5f2 155
6da3c1 156   // 重置登录请求标记
J 157   var we_session = fn.getLocalStorage('we_session')
158   if (we_session && we_session.we_session) {
159     g_flag_login_requested = false
160   }
3ac5f2 161 }
J 162
163 // 请求后
6da3c1 164 function afterRequest(_res) {
J 165   // console.log('请求后')
3ac5f2 166 }
J 167
168 // 处理返回数据
169 // @return {Object} 处理过的数据
6da3c1 170 function successChangeData(res) {
J 171   return res
3ac5f2 172 }
J 173
174 // 批量请求完成
6da3c1 175 function afterMultiRequests(request_option) {
J 176   // console.log("多个请求结束之后")
177   // 关闭loading
178   if (g_flag_loading) {
179     // wx.hideLoading()
180     endLoading(request_option)
181     g_flag_loading = false
182   }
3ac5f2 183 }
J 184
6da3c1 185 function updateKey(res, key) {
J 186   // 更新 key 值
187   if (res.request_option.method === 'GET' && (!res.request_option.udData || !res.request_option.udData.nokey)) {
188     res.request_option.url = res.request_option.url.replace(/mpToken=[^&]*/g, `mpToken=${key}`)
189   }
190   if (res.request_option.method === 'POST' && (!res.request_option.udData || !res.request_option.udData.nokey)) {
191     res.request_option.data.mpToken = key
192   }
193   return res
3ac5f2 194 }
J 195
196 // 模拟数据处理流程
6da3c1 197 function mockFlow(res) {
J 198   return new Promise(async(resolve, _reject) => {
199     // 打印请求信息
200     res.http_option.debug && console.log('模拟请求', res.request_option)
3ac5f2 201
6da3c1 202     var mockData = res.request_option.mockData || { code: 100, data: {}, message: 'success' }
3ac5f2 203
6da3c1 204     // 打印返回信息
J 205     res.http_option.debug && console.log('模拟返回', { data: mockData })
206     res.http_option.debug && console.log('开始模拟等待800ms')
207     var timer = setTimeout(() => {
208       clearTimeout(timer)
209       // 关闭loading
210       if (g_flag_loading) {
211         // wx.hideLoading()
212         endLoading(res.request_option)
213         g_flag_loading = false
214       }
215       res.http_option.debug && console.log('结束模拟等待800ms')
216       if (res.request_option.udData && res.request_option.fullData) {
217         resolve({ data: mockData })
218       } else {
219         resolve(mockData)
220       }
221     }, 800)
222   })
3ac5f2 223 }
J 224
225 // 请求前处理流程
6da3c1 226 function beforeFlow(res) {
J 227   return new Promise(async(resolve) => {
228     // 预留请求前处理
229     // 设置为true,下次处理跳过 beforeFlow,避免死循环
230     res.request_option.skip_before_flow = true
231     // 再次请求
232     resolve(res.Request(res.request_option))
233   })
3ac5f2 234 }
J 235
236 // 预留其余处理
6da3c1 237 function configRequest() {
J 238   return new Promise((resolve, reject) => {
239     resolve({})
240   })
3ac5f2 241 }
J 242
243 // 登录处理
6da3c1 244 function appLogin(option = {}) {
J 245   return new Promise((resolve, reject) => {
246     // Login.checkLogin({
247     //     force: !!option.forceLogin,
248     //     callback: (key)=>{
249     //         resolve(key)
250     //     }
251     // })
252     Login.toLongUrl()
253   })
3ac5f2 254 }
J 255
256 // 请求后处理
6da3c1 257 function afterFlow(res) {
J 258   return new Promise((resolve, reject) => {
259     var data = res.res.data
260     // console.log('0000000000000000000', res)
261     // 登录超时
262     if (
263       (data && data.res && data.res.status == 2) ||
264             (data && data.code == 603)
265     ) {
266       res.http_option.debug && console.log('登录超时,需要重新登录', res.res)
267       // 登录超时,需要重新登录
268       // 清空we_session
269       // getApp().globalData.we_session = null
270       // fn.removeLocalStorage('we_session')
271       // resolve(retryLogin(res))
272       // todo
273       // // 清空登录凭证和用户数据
274       // sessionStorage.clear()
275       // // 未登录,跳转登录页面
276       // this.$router.replace({ path: '/login' })
277       return
278     }
3ac5f2 279
6da3c1 280     // status不为0
J 281     if (
282       (data && data.res && data.res.status != 0) ||
283             (data && data.code != 100)
284     ) {
285       if (data.res) {
286         console.error('status不为0:' + (res.res.errMsg || ''), res.res)
287         // 弹出提示
288         // wx.showModal({
289         //     title: '请求提示',
290         //     content: data.res.errMsg || `请求有误,status=${data.res.status}`,
291         //     confirmText: '确定',
292         //     confirmColor: '#576B95',
293         //     showCancel: false
294         // })
3ac5f2 295
6da3c1 296         // element-ui
J 297         // Message.error(data.res.errMsg || `请求有误,status=${data.res.status}`)
3ac5f2 298
6da3c1 299         // 根据status处理
J 300         if (typeof resStatusCode['status' + data.res.status] === 'function') {
301           resStatusCode['status' + data.res.status](data)
302         }
303       }
3ac5f2 304
6da3c1 305       if (typeof data.code !== 'undefined') {
J 306         console.error('code不为100:' + data.code, data.msg, res.res)
307       }
3ac5f2 308
6da3c1 309       reject(res.res)
J 310       return
311     }
3ac5f2 312
6da3c1 313     // status为空
J 314     if (data && !data.res && typeof data.code === 'undefined') {
315       console.error('status为空', res.res)
316       let tips = ''
317       if (res.res.statusCode == '500') {
318         tips = '当前网络状态不佳,请稍后再试:statusCode=500;'
319       } else if (res.res.statusCode == '200') {
320         if (typeof res.data === 'string') {
321           tips = filterHtml(res.data)
322         }
323         if (typeof res.data === 'object') {
324           tips = filterHtml(JSON.stringify(res.data))
325         }
326         tips = '网络状况不佳,点击确定重试:statusCode=200;' + tips
327       } else {
328         tips = `连接服务器失败,点击确定重试:statusCode=${res.res.statusCode};`
329       }
330       // 请求提示
3ac5f2 331
6da3c1 332       // 小程序
J 333       // wx.showModal({
334       //     title: '请求提示',
335       //     content: tips,
336       //     confirmText: '确定',
337       //     confirmColor: '#576B95',
338       //     showCancel: false,
339       //     success (res) {
340       //         if (res.confirm) {
341       //             // 点击确认后重新请求
342       //             resolve(res.Request(res.request_option))
343       //         }
344       //     }
345       // })
346
347       // element-ui
348       // MessageBox.alert(tips, '网络提示', {
349       //     confirmButtonText: '确定',
350       //     type: 'error'
351       // }).then(()=>{
352       //     resolve(res.Request(res.request_option))
353       // }).catch(()=>{
354       //     // 点击取消
355       // })
356       return
357     }
358
359     // 打印返回信息
360     res.http_option.debug && console.log('返回', res.res)
361     if (res.request_option.udData) {
362       // 返回全部数据
363       if (res.request_option.udData.fullData === true) {
364         resolve(res.res)
365       }
366     }
367     g_login_counter && (g_login_counter = 0)
368     resolve(data)
369   })
3ac5f2 370 }
J 371
372 // 重新登录
6da3c1 373 async function retryLogin(res) {
J 374   // 次数+1
375   g_login_counter++
376   return new Promise(async(resolve, _reject) => {
377     // 等待登录
378     var login_result = await appLogin({ forceLogin: true })
379     // 登录失败
380     if (!login_result && g_login_counter < g_LOGIN_MAX) {
381       // 2秒后重试
382       var timer = setTimeout(() => {
383         clearTimeout(timer)
384         resolve(retryLogin(res))
385       }, 2000)
386     }
387     // 登录成功
388     if (login_result) {
389       // 更新key值
390       res = updateKey(res, login_result)
391       // 再次请求
392       resolve(res.Request(res.request_option))
393     }
394   })
3ac5f2 395 }
J 396
397 export default {
6da3c1 398   httpEventCode,
3ac5f2 399
6da3c1 400   getChangeRequestOption,
J 401   postChangeRequestOption,
402   successChangeData,
3ac5f2 403
6da3c1 404   beforeRequest,
J 405   afterRequest,
406   afterMultiRequests,
407
408   mockFlow,
409   beforeFlow,
410   afterFlow
411 }