children117cl
2021-05-27 ccad616880f2f6e21adf18f6f4e28de9930ff05e
提交 | 用户 | age
2a61f6 1 const axios = require('axios')
L 2 import { Message } from 'element-ui'
3 import { getToken } from '@/utils/auth'
4 function isF() { return typeof arguments[0] === 'function' }
5
6 /* json转formdata(序列化),仅支持一级字面量和字面量数组 */
7 function jsonToFormData(json) {
8   var arr = []
9   var e = encodeURIComponent
10   for (var key in json) {
11     var item = json[key]
12     var res
13     if (item instanceof Array) {
14       res = []
15       item.map(function(o) {
16         res.push(e(key) + '=' + e(o))
17       })
18       res = res.join('&')
19     } else {
20       res = e(key) + '=' + e(item)
21     }
22     arr.push(res)
23   }
24   return arr.join('&')
25 }
26
27 function Http(http_o) {
28   // 返回值 Object
29   // 参数说明
30   // o.baseUrl 这个参数根据传入的基础路径会初始化http中的所有请求方法
31   // ... 待扩展
32   var requestArr = [] // 请求次数
33   return {
34     // 这个对象是包含全部所有的请求
35     postFN(post_o, successCallBack, failCallBack) {
36       // post 方法
37       // 参数说明
38       // post_o.url 指的是请求的路径
39       // post_o.baseChgUrl 可动态切换的接口
40       // params 接受 对象序列化 传参 即 将传入的 params(对象) 参数  序列化为 url 传参的方式如 xxx.com/api?id=1212&name=456
41       // udData Object:即userDefined Data 用户自定义数据,这是一个扩展字段
42       // mockData Object 测试数据
43       Request({
44         method: 'post',
45         header: post_o.header,
46         params: post_o.params || false,
47         url: post_o.url,
48         baseChgUrl: post_o.baseChgUrl, // 动态切换接口
49         udData: post_o.udData, // 预留扩展字段
50         mockData: post_o.mockData // 测试数据
51       }).then(data => {
52         console.log('请求:', post_o.url, data, post_o.params)
53         // 登录失效
54         if (Number(data.code) === 603) {
55           Message({
56             type: 'error',
57             showClose: true,
58             duration: 10000,
59             message: data.msg
60           })
61           setTimeout(() => {
62             sessionStorage.clear()
63             // 未登录,刷新页面出发页面 checkLoginFN跳转登录页面
64             location.reload()
65           }, 800)
66           return
67         }
68
69         // todo 无code时的报错
70         if (Number(data.code) === 100) {
71           // 请求成功
72           isF(successCallBack) && successCallBack(data.data)
73         } else {
74           // 请求失败
75           if (isF(failCallBack)) {
76             failCallBack(data)
77           } else {
78             Message({
79               type: 'error',
80               showClose: true,
81               duration: 10000,
82               message: data.msg
83             })
84           }
85         }
86       })
87     },
88     getFN(get_o, successCallBack, failCallBack) {
89       // get 方法
90       // 参数说明
91       // get_o.url 指的是请求的路径
92       // get_o.baseChgUrl 可动态切换的接口
93       // params 接受 对象序列化 传参 即 将传入的 params(对象) 参数  序列化为 url 传参的方式如 xxx.com/api?id=1212&name=456
94       // udData Object:即userDefined Data 用户自定义数据,这是一个扩展字段
95       // mockData Object 测试数据
96       Request({
97         method: 'get',
98         header: get_o.header,
99         params: get_o.params || false,
100         url: get_o.url,
101         baseChgUrl: get_o.baseChgUrl, // 动态切换接口
102         udData: get_o.udData, // 预留扩展字段
103         mockData: get_o.mockData // 测试数据
104       }).then(data => {
105         console.log('请求:', get_o.url, data, get_o.params)
106         // 登录失效
107         if (Number(data.code) === 603) {
108           Message({
109             type: 'error',
110             showClose: true,
111             duration: 10000,
112             message: data.msg
113           })
114           setTimeout(() => {
115             sessionStorage.clear()
116             // 未登录,刷新页面出发页面 checkLoginFN跳转登录页面
117             location.reload()
118           }, 800)
119           return
120         }
121
122         if (Number(data.code) === 100) {
123           // 请求成功
124           isF(successCallBack) && successCallBack(data.inf)
125         } else {
126           // 请求失败
127           if (isF(failCallBack)) {
128             failCallBack(data)
129           } else {
130             Message({
131               type: 'error',
132               showClose: true,
133               duration: 10000,
134               message: data.msg
135             })
136           }
137         }
138       })
139     }
140   }
141
142   function Request(request_o) {
143     // 总请求方法,这是一个被独立处理出来的方法,因为这个方法是一个比较特殊的方法,首先这个方法不应被暴露出来,
144     // 然后因为根据项目的独特性,最底层的拦截、加密、权限的实现和代码都有所不同,这里应该独立处理,方便以后移植和复用
145     // 这个方法是所有请求方法的底层方法,具有错误码拦截,权限管理(鉴权)等 拦截的功能
146     // 返回值 Object
147     // 参数说明
148     // o.method 请求类型
149     // o.url 请求路径
150     // o.params 请求参数
151     // o.baseUrl 基本路径
152     // udData Object:即userDefined Data 用户自定义数据,这是一个扩展字段
153     //              fullData 这个字段为真的话,将返回 服务端返回的所有数据,默认返回data
cadf24 154     // 20210303 long 优化请求结束loading 将noLoading不计算如请求数组
L 155     if (request_o && (!request_o.udData || !request_o.udData.noLoading)) {
156       requestArr.push(request_o) // 将请求加入数组
157     }
158     // requestArr.push(request_o) // 将请求加入数组
2a61f6 159     if (http_o.startRequest) {
L 160       http_o.startRequest(http_o, request_o) // 事件委托,请求之前
161     }
162     return new Promise((resolve, reject) => {
163       // 添加切换调用接口域名功能 -- start
164       var ajaxUrl
165       if (request_o.baseChgUrl) {
166         ajaxUrl = request_o.baseChgUrl + request_o.url
167       } else {
168         ajaxUrl = http_o.baseUrl + request_o.url
169       }
170       // 添加切换调用接口域名功能 -- end
171
172       // 处理传参 -- start
173       // 将token放到params里
174       var noToken = request_o.udData && request_o.udData.noToken // noToken则不传token
175       var adminToken = getToken()
176       // 放到连接后得请求参数
177
178       var urlEncodes = {}
179       if (adminToken && !noToken) {
180         urlEncodes = { adminToken: adminToken }
181         // ...urlEncodes,
182       }
183       // // 将请求参数放到链接后面
ad3cc5 184       var paramsUrl = urlEncode(urlEncodes)
cadf24 185       if (!/\?/.test(ajaxUrl)) {
L 186         paramsUrl = paramsUrl.replace('&', '?')
ad3cc5 187       }
2a61f6 188       ajaxUrl = ajaxUrl + paramsUrl
L 189
190       // console.log(ajaxUrl)
191       // console.log(request_o.params)
192       // 处理传参 -- end
193
194       // request_o.params.adminToken = adminToken
195
196       var requestConfig = {
197         // 請求對象
198         method: request_o.method,
199         url: ajaxUrl,
200         data: request_o.params,
201         header: request_o.header || {
202           'Content-type': 'application/x-www-form-urlencoded' // 默认值
203         }
204       }
205
206       // 转formData
207       if (requestConfig.header['Content-type'] === 'application/x-www-form-urlencoded') {
208         requestConfig.data = requestConfig.data ? jsonToFormData(requestConfig.data) : {}
209       }
210
211       // 使用测试数据
212       if (http_o.isMock) {
213         console.log('开始模拟等待800ms')
214         // 模拟请求
215         if (http_o.httpEventCode && http_o.httpEventCode['code200']) {
216           http_o.httpEventCode['code200'](request_o.mockData) // 事件委托,处理错误
217         }
218         if (http_o.endRequest) {
219           http_o.endRequest({ ...http_o, ...request_o.mockData }) // 事件委托,请求之前
220         }
221         setTimeout(() => {
222           console.log('结束模拟等待800ms')
223           resolve(request_o.mockData)
224
225           // 无论成功或者失败都会执行
226           requestArr.splice(0, 1)
227           if (requestArr.length === 0) {
228             // 批量请求全部完成
229             if (http_o.concurrentRequests) {
230               http_o.concurrentRequests()
231             }
232           }
233         }, 800)
234         return
235       }
236
237       axios(requestConfig).then((res) => {
238         if (http_o.httpEventCode && http_o.httpEventCode['code' + res.status]) {
239           http_o.httpEventCode['code' + res.status](res) // 事件委托,处理错误
240         }
241         if (http_o.endRequest) {
242           http_o.endRequest({ ...http_o, ...res }) // 事件委托,请求之前
243         }
244         if (http_o.defindFlow) {
245           // 自定义流程
246           resolve(http_o.defindFlow({ requestConfig: requestConfig, res: res, Request: Request }))
247         }
248         if (request_o.udData && request_o.udData.fullData === true) {
249           // 如果这里的fullData 为真的话,将返回服务器返回的所有数据
250           resolve(res)
251         }
252         resolve(res.data)
253       }).catch((err) => {
254         // console.log('异步报错:',err);
255         var code
256         err.response && (code = err.response.status) // 请求错误码
257         if (http_o.httpEventCode && http_o.httpEventCode['code' + code]) {
258           http_o.httpEventCode['code' + code](err) // 事件委托,处理错误
259         }
260         reject(err)
261       }).finally(() => {
262         // 无论成功或者失败都会执行
263         requestArr.splice(0, 1)
264         if (requestArr.length === 0) {
265           // 批量请求全部完成
266           if (http_o.concurrentRequests) {
267             http_o.concurrentRequests()
268           }
269         }
270       })
271     })
272   }
273
274   // 对象转url参数
275   function urlEncode(param, key, encode) {
276     if (param == null) return ''
277     var paramStr = ''
278     var t = typeof (param)
279     if (t === 'string' || t === 'number' || t === 'boolean') {
280       paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param)
281     } else {
282       for (var i in param) {
283         var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
284         paramStr += urlEncode(param[i], k, encode)
285       }
286     }screenLeft
287     return paramStr
288   }
289 }
290 export { Http }