liweilong
2020-10-30 2a61f64ebeeec3fff23b7adbce8c7fbfc54add51
提交 | 用户 | 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
154     requestArr.push(request_o) // 将请求加入数组
155     if (http_o.startRequest) {
156       http_o.startRequest(http_o, request_o) // 事件委托,请求之前
157     }
158     return new Promise((resolve, reject) => {
159       // 添加切换调用接口域名功能 -- start
160       var ajaxUrl
161       if (request_o.baseChgUrl) {
162         ajaxUrl = request_o.baseChgUrl + request_o.url
163       } else {
164         ajaxUrl = http_o.baseUrl + request_o.url
165       }
166       // 添加切换调用接口域名功能 -- end
167
168       // 处理传参 -- start
169       // 将token放到params里
170       var noToken = request_o.udData && request_o.udData.noToken // noToken则不传token
171       var adminToken = getToken()
172       // 放到连接后得请求参数
173
174       var urlEncodes = {}
175       if (adminToken && !noToken) {
176         urlEncodes = { adminToken: adminToken }
177         // ...urlEncodes,
178       }
179       // // 将请求参数放到链接后面
180       var paramsUrl = urlEncode(urlEncodes).replace('&', '?')
181       ajaxUrl = ajaxUrl + paramsUrl
182
183       // console.log(ajaxUrl)
184       // console.log(request_o.params)
185       // 处理传参 -- end
186
187       // request_o.params.adminToken = adminToken
188
189       var requestConfig = {
190         // 請求對象
191         method: request_o.method,
192         url: ajaxUrl,
193         data: request_o.params,
194         header: request_o.header || {
195           'Content-type': 'application/x-www-form-urlencoded' // 默认值
196         }
197       }
198
199       // 转formData
200       if (requestConfig.header['Content-type'] === 'application/x-www-form-urlencoded') {
201         requestConfig.data = requestConfig.data ? jsonToFormData(requestConfig.data) : {}
202       }
203
204       // 使用测试数据
205       if (http_o.isMock) {
206         console.log('开始模拟等待800ms')
207         // 模拟请求
208         if (http_o.httpEventCode && http_o.httpEventCode['code200']) {
209           http_o.httpEventCode['code200'](request_o.mockData) // 事件委托,处理错误
210         }
211         if (http_o.endRequest) {
212           http_o.endRequest({ ...http_o, ...request_o.mockData }) // 事件委托,请求之前
213         }
214         setTimeout(() => {
215           console.log('结束模拟等待800ms')
216           resolve(request_o.mockData)
217
218           // 无论成功或者失败都会执行
219           requestArr.splice(0, 1)
220           if (requestArr.length === 0) {
221             // 批量请求全部完成
222             if (http_o.concurrentRequests) {
223               http_o.concurrentRequests()
224             }
225           }
226         }, 800)
227         return
228       }
229
230       axios(requestConfig).then((res) => {
231         if (http_o.httpEventCode && http_o.httpEventCode['code' + res.status]) {
232           http_o.httpEventCode['code' + res.status](res) // 事件委托,处理错误
233         }
234         if (http_o.endRequest) {
235           http_o.endRequest({ ...http_o, ...res }) // 事件委托,请求之前
236         }
237         if (http_o.defindFlow) {
238           // 自定义流程
239           resolve(http_o.defindFlow({ requestConfig: requestConfig, res: res, Request: Request }))
240         }
241         if (request_o.udData && request_o.udData.fullData === true) {
242           // 如果这里的fullData 为真的话,将返回服务器返回的所有数据
243           resolve(res)
244         }
245         resolve(res.data)
246       }).catch((err) => {
247         // console.log('异步报错:',err);
248         var code
249         err.response && (code = err.response.status) // 请求错误码
250         if (http_o.httpEventCode && http_o.httpEventCode['code' + code]) {
251           http_o.httpEventCode['code' + code](err) // 事件委托,处理错误
252         }
253         reject(err)
254       }).finally(() => {
255         // 无论成功或者失败都会执行
256         requestArr.splice(0, 1)
257         if (requestArr.length === 0) {
258           // 批量请求全部完成
259           if (http_o.concurrentRequests) {
260             http_o.concurrentRequests()
261           }
262         }
263       })
264     })
265   }
266
267   // 对象转url参数
268   function urlEncode(param, key, encode) {
269     if (param == null) return ''
270     var paramStr = ''
271     var t = typeof (param)
272     if (t === 'string' || t === 'number' || t === 'boolean') {
273       paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param)
274     } else {
275       for (var i in param) {
276         var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
277         paramStr += urlEncode(param[i], k, encode)
278       }
279     }screenLeft
280     return paramStr
281   }
282 }
283 export { Http }