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