long
2024-05-13 6e089f294207e13459ad872a2fb6e701721f5506
提交 | 用户 | age
3ac5f2 1 /**
J 2  * Http 请求
3  * * 小程序请使用增强编译
6da3c1 4  *
3ac5f2 5  * 调用例子
J 6  * Req.http.post({
7  *     url: '',
8  *     data: {},
9  * })
10  */
11
12 import Axios from '../libs/axios'
13
14 /* json转formdata(序列化),仅支持一级字面量和字面量数组 */
6da3c1 15 function jsonToFormData(json) {
J 16   var arr = []
17   var e = encodeURIComponent
18   for (var key in json) {
19     var item = json[key]
20     var res
21     if (item instanceof Array) {
22       res = []
23       item.map(function(o) {
24         res.push(e(key) + '=' + e(o))
25       })
26       res = res.join('&')
27     } else {
28       res = e(key) + '=' + e(item)
3ac5f2 29     }
6da3c1 30     arr.push(res)
J 31   }
32   return arr.join('&')
3ac5f2 33 }
J 34
35 /**
36  * Http 类
37  * @param http_option {Object}
38  * -@key {string}   baseUrl --请求链接前置
39  * -@key {object}   getChangeRequestParameter --get请求参数
40  * -@key {object}   postChangeRequestParameter --post请求参数
41  * -@key {function} beforeRequest --请求前处理
42  * -@key {function} beforeFlow --请求前流程
43  * -@key {function} successChangeData --请求完成后,处理数据
44  * -@key {function} httpEventCode --请求完成后,处理委托
45  * -@key {function} afterFlow --请求完成后流程
46  * -@key {function} afterRequest --请求后事件
47  * -@key {function} afterMultiRequests --同时多次请求完成之后 
48  */
49 function Http (http_option) {
50     // 请求配置数组,标记是否批量请求
51     var requestArr = []
52     // 请求总线
53     function Request (request_option) {
54         // 默认 data 为对象
55         request_option.data = request_option.data || {}
56         // 请求配置加入数组
57         requestArr.push(request_option)
58
59         // 触发请求前事件
60         if (http_option.beforeRequest) {
61             http_option.beforeRequest({http_option, request_option})
62         }
63         // 使用 promise 完成请求
64         return new Promise ((resolve, reject) => {
65             // vue-cli中改用mockjs
66             // mock假数据流程
67             // 20210121 - 暂停使用mockjs
68             if (http_option.mockFlow && http_option.ismock) {
69                 resolve(http_option.mockFlow({http_option, Request, request_option}))
70                 return 
71             }
72             // 请求前自定义流程
73             if (http_option.beforeFlow && !request_option.skip_before_flow) {
74                 // skip 为 true 时,不仅如此此流程
75                 requestArr.splice(0, 1)
76                 resolve(http_option.beforeFlow({http_option, Request, request_option}))
77                 return
78             }
79             var url = request_option.url
80             if (!url) {
81                 throw new Error('url不能为空')
82             }
83             // 不增加domain设定
84             if (request_option.udData && request_option.udData.nodomain) {
85                 if (!/^https?:\/\//.test(url)) {
86                     // 使用本项目域名
87                     if (/^\//.test(url)) {
88                         url = location.origin + url
89                     } else {
90                         // 修复访问本地json问题
91                         url = location.origin + location.pathname.replace('index.html', '') + url
92                     }
93                 }
94             } else if (!/^https?:\/\//.test(url)) {
95                 url = http_option.baseUrl + url
96             }
97             // 定义请求配置
98             var request_config = {
99                 method: request_option.method,
100                 url,
101                 data: request_option.data,
102                 header: request_option.header || {'Content-type':'application/x-www-form-urlencoded'},
103                 // 请求成功
104                 success (res) {
105                     // 请求成功后,处理数据
106                     if (http_option.successChangeData) {
107                         res = http_option.successChangeData(res)
108                     }
109                     // 触发 code 委托事件
110                     if (http_option.httpEventCode && http_option.httpEventCode['code'+res.status]) {
111                         http_option.httpEventCode['code'+res.status](res);
112                     }
113                     // 请求后自定义流程
114                     if (http_option.afterFlow) {
115                         resolve(http_option.afterFlow({
116                             res,
117                             request_config,
118                             request_option,
119                             http_option,
120                             Request,
121                         }))
122                     }
123                     // 触发请求后事件
124                     if (http_option.afterRequest) {
125                         http_option.afterRequest({http_option, res})
126                     }
127
128                     if (request_option.udData) {
129                         // 返回全部数据
130                         if (request_option.udData.fullData === true) {
131                             resolve(res)
132                         }
133                     }
134                     resolve(res.data)
135                 },
136
137                 // 请求失败
138                 fail (err) {
139                     // console.error(err)
140                     var code = err.response && err.response.status
141                     // 触发 code 委托事件
142                     if (code && http_option.httpEventCode && http_option.httpEventCode['code'+code]) {
143                         http_option.httpEventCode['code'+code](err, url)
144                     }
145                     // alert('请求失败,错误代号:'+code)
146                     reject(err)
147                 },
148
149                 // 无论成功或者失败都会执行
150                 complete () {
151                     requestArr.splice(0, 1)
152                     if (requestArr.length === 0) {
153                         // http_option.debug && console.log('触发 afterMultiRequests', request_config)
154                         // 批量请求全部完成,触发事件
155                         if (http_option.afterMultiRequests) {
156                             http_option.afterMultiRequests(request_option)
157                         }
158                     }
159                 }
160             };
161
162             // get 方法时,去掉 data
163             if (request_option.method === 'GET') {
164                 delete request_config.data
165             }
166
167             // 打印请求信息
168             http_option.debug && console.log('请求', request_config)
169             // 处理header和data的关系
170             if (request_config.header['Content-type'] == 'application/x-www-form-urlencoded') {
171                 request_config.data = request_config.data ? jsonToFormData(request_config.data) : {}
172             }
173
174             // 开始请求
175             // wx.request(request_config)
176             Axios({
177                 method: request_config.method,
178                 headers: request_config.header,
179                 url: request_config.url,
180                 data: request_config.data
181             }).then((res) => {
182                 // http_option.debug && console.log('成功回调', res)
183                 request_config.success(res)
184                 request_config.complete(res)
185             }).catch((res) => {
186                 // http_option.debug && console.log('失败回调', res)
187                 request_config.fail(res)
188                 request_config.complete(res)
189             })
190         })
191     }
192
193     var obj = {
194         // get请求
195         // @param get_option {Object} 请求配置
196         // -@key url {String} 请求路径
197         // -@key params {Object} 请求参数
198         // -@key udData {Object} 自定义扩展字段
199
200         // @return {Promise}
201         get (get_option) {
202             // 请求前,统一处理请求参数
203             if (http_option.getChangeRequestOption) {
204                 get_option = http_option.getChangeRequestOption(get_option)
205             }
206
207             // params对象序列化到url中
208             if (get_option.params) {
209                 let arr = []
210                 for (let i in get_option.params) {
211                     if (get_option.params.hasOwnProperty(i)) {
212                         arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(get_option.params[i]))
213                     }
214                 }
215                 if (/\?/.test(get_option.url)) {
216                     get_option.url += '&' + arr.join('&')
217                 } else {
218                     get_option.url += '?' + arr.join('&')
219                 }
220                 
221             }
222
223             // 使用promise完成Request调用
224             return new Promise ((resolve, reject) => {
225                 Request({
226                     method: 'GET',
227                     url: get_option.url,
228                     udData: get_option.udData,
229                     header: get_option.header,
230                     mockData: get_option.mockData,
231                 }).then((data) => {
232                     resolve(data)
233                 }).catch((res)=>{
234                     // ↓↓↓↓↓↓↓↓↓↓ 临时处理失败
235                     // var junPage = getApp().getCurPage()
236                     // junPage = junPage && junPage.selectComponent('#junPage')
237                     // if (junPage && junPage.fail) {
238                     //     console.log('设置fail')
239                     //     junPage.fail()
240                     // }
241                     // ↑↑↑↑↑↑↑↑↑↑ 临时处理失败
242                     reject(res)
243                 })
244             })
245         },
246
247         // post请求
248         // @param post_option {Object} 请求配置
249         // -@key url {String} 请求路径
250         // -@key data {Object} 请求参数
251         // -@key udData {Object} 自定义扩展字段
252
253         // @return {Promise}
254         post (post_option) {
255             // 请求前,统一处理请求参数
256             if (http_option.postChangeRequestOption) {
257                 post_option = http_option.postChangeRequestOption(post_option)
258             }
259             // 使用promise完成Request调用
260             return new Promise ((resolve, reject) => {
261                 Request({
262                     method: 'POST',
263                     url: post_option.url,
264                     data: post_option.data,
265                     udData: post_option.udData,
266                     header: post_option.header,
267                     mockData: post_option.mockData,
268                 }).then((data) => {
269                     resolve(data)
270                 }).catch((res)=>{
271                     // ↓↓↓↓↓↓↓↓↓↓ 临时处理失败
272                     // var junPage = getApp().getCurPage()
273                     // junPage = junPage && junPage.selectComponent('#junPage')
274                     // if (junPage && junPage.fail) {
275                     //     console.log('设置fail')
276                     //     junPage.fail()
277                     // }
278                     // ↑↑↑↑↑↑↑↑↑↑ 临时处理失败
279                     reject(res)
280                 })
281             })
282         }
283     }
284     obj.getFN = obj.get
285     obj.postFN = obj.post
286     return obj;
287 }
288
289 export default Http