http.js
10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import sign from './sign.js'
import { secretKey, pathEnum, domain, djDomain, merchantDomain, djSecretKey, shukeDomain } from '../../env'
const HOST = {
scrm: domain,
dj: djDomain,
merchant: merchantDomain,
ip: 'http://192.168.1.125:8080'
}
class Request {
get (params, returnAll = false, hostType) {
return this.request('GET', params, returnAll, hostType)
}
post (params, returnAll = false, hostType) {
return this.request('POST', params, returnAll, hostType)
}
fetch (method, data, returnAll = true, hostType) {
return this.post(
{
method,
...data
},
returnAll,
hostType
)
}
request (RequestMethods, params, returnAll, hostType = 'dj') {
return new Promise((resolve, reject) => {
let _this = this
uni.getNetworkType({
success (res) {
if (res.networkType == 'none') {
uni.hideLoading()
uni.showToast({
title: '网络异常',
icon: 'none'
})
reject('网络异常')
return
}
let header =
RequestMethods === 'POST'
? {
'content-type': 'application/x-www-form-urlencoded'
}
: {
'Cache-Control': 'no-cache'
}
let projectName = params.projectName
if (!projectName) projectName = _this.getRopProject(params.method)
const path = pathEnum[projectName]
params = _this.getData(params, hostType)
uni.request({
url: `${HOST[hostType]}${path}router?method=${params.method}`,
data: params,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success (response) {
try {
/**业务代码 */
let { data, statusCode } = response
if (!data || statusCode != 200) {
uni.hideLoading()
let errMsg = ''
if (!data) errMsg = '获取数据失败,请重试。'
else errMsg = '服务器暂时不可用,请稍后再次尝试。'
uni.$logger.error(`Request Fail: ${JSON.stringify(params)}->${errMsg}`)
return reject(errMsg)
}
let { code, message } = data
if (returnAll) {
resolve(data)
return
}
if (code == 20 || code == 21) {
const pages = getCurrentPages(),
currentPage = pages[pages.length - 1]
uni.$logger.local.warn(`HTTP Triggered Logout: params:${JSON.stringify(params)} method: ${params.method}->code:${code} msg:${message} currentPage:${currentPage.route}`)
uni.hideLoading()
if (currentPage.route != 'pages/common/login') {
uni.reLaunch({
url: '/pages/common/login'
})
}
} else {
if (code == '0') {
resolve(data.data)
} else {
uni.hideLoading()
uni.showToast({
title: message || '系统异常',
icon: 'none'
})
uni.$logger.error(`HTTP Request Error: ${JSON.stringify(params)}->${message}`)
}
}
} catch (error) {
uni.$logger.error(`${params.method}处理异常:${error.message}`)
reject(error)
}
},
fail (error) {
uni.hideLoading()
uni.$logger.error(`HTTP Request Fail: ${JSON.stringify(params)}->${error.message}`)
// console.error(`${params.method}接口异常:`, error)
uni.showToast({
title: typeof error == 'string' ? error : error.errMsg ? error.errMsg : JSON.stringify(error) || '系统异常',
icon: 'error'
})
reject(error)
},
complete () {
uni.stopPullDownRefresh()
}
})
}
})
})
}
getData (params, hostType = 'scrm') {
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
else delete params.projectName
let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
if (secretKey[projectName]) {
appKey = secretKey[projectName].appKey
secret = secretKey[projectName].secret
}
if (hostType == 'dj') {
appKey = djSecretKey.appKey
secret = djSecretKey.secret
}
let { sessionId } = uni.$storage.get()
let noSignAttr = []
if (!params.sessionId && sessionId) params.sessionId = sessionId
if (params.delSessionId) {
delete params.sessionId
delete params.delSessionId
}
if (params.noSignAttr) {
noSignAttr = params.noSignAttr
delete params.noSignAttr
}
params.v = '1.0.0'
params.format = 'json'
params.locale = 'zh_CN'
params.source = 'app'
params.appKey = appKey
return sign(params, secret, noSignAttr)
}
getRopProject (method) {
const projectName = method.split('.')[2]
return projectName
}
uni_request ({ url, method = 'GET', data = {}, header = {}, dataType = 'json', responseType = 'text' }) {
return new Promise(resolve => {
uni.request({
url,
data,
method,
header,
dataType,
responseType,
success (response) {
resolve(response.data)
}
})
})
}
shukeRequest (url, params = {}, method = 'GET', returnAll = false) {
let header =
method === 'POST'
? {
'content-type': 'application/json'
}
: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/json'
}
let { sessionId } = uni.$storage.get()
if (sessionId) header.Authorization = sessionId
const _this = this
return new Promise((resolve, reject) => {
uni.getNetworkType({
success (res) {
if (res.networkType == 'none') {
uni.hideLoading()
uni.showToast({
title: '网络异常',
icon: 'none'
})
reject('网络异常')
return
}
uni.request({
url: `${shukeDomain}/${url}`,
data: params,
method,
header,
dataType: 'json',
responseType: 'text',
success (response) {
try {
let { data, statusCode } = response
if (!data || statusCode != 200) {
uni.hideLoading()
let errMsg = ''
if (!data) errMsg = '获取数据失败,请重试。'
else errMsg = '服务器暂时不可用,请稍后再次尝试。'
uni.$logger.error(`Request Fail: ${JSON.stringify(params)}->${errMsg}`)
return reject(errMsg)
}
if (returnAll) {
resolve(data)
return
}
let { code, msg } = data
if (code == 401) {
// 调用 restore 接口尝试恢复登录
const currentSessionId = uni.$storage.get('sessionId')
if (currentSessionId) {
_this.restoreLogin(resolve, reject, url, params, method, returnAll, currentSessionId)
} else {
// 没有 sessionId,直接跳转登录
_this.redirectToLogin(reject)
}
return
} else {
resolve(data.data)
}
} catch (error) {
uni.$logger.error(`${params.method}处理异常:${error.msg}`)
reject(error)
}
},
fail (error) {
uni.hideLoading()
uni.$logger.error(`HTTP Request Fail: ${JSON.stringify(params)}->${error.message}`)
uni.showToast({
title: typeof error == 'string' ? error : error.errMsg ? error.errMsg : JSON.stringify(error) || '系统异常',
icon: 'error'
})
reject(error)
}
})
}
})
})
}
/**
* 调用 restore 接口恢复登录
*/
restoreLogin (resolve, reject, url, params, method, returnAll, currentSessionId) {
uni.request({
url: `${shukeDomain}/linkwe-gateway/auth/accountLoginSp/restore`,
data: { token: currentSessionId },
method: 'POST',
header: { 'content-type': 'application/json' },
success: (restoreRes) => {
console.log(restoreRes, 'restoreRes')
const restoreData = restoreRes.data
if (restoreData && restoreData.code == '200') {
// 恢复成功,更新 sessionId 和 userInfo
const newToken = restoreData.data?.sessionId || restoreData.data?.token || restoreData.data?.access_token
const userInfo = restoreData.data?.loginUser || restoreData.data?.user || {}
if (newToken) {
uni.$storage.set('sessionId', newToken)
}
if (userInfo && Object.keys(userInfo).length > 0) {
uni.$storage.set('userInfo', userInfo)
}
// 重新发起原请求
resolve(this.shukeRequest(url, params, method, returnAll))
} else {
// restore 返回失败,跳转登录
this.redirectToLogin(reject)
}
},
fail: () => {
// restore 接口调用失败,跳转登录
this.redirectToLogin(reject)
}
})
}
/**
* 跳转到登录页
*/
redirectToLogin (reject) {
uni.$storage.set('sessionId', '')
uni.$storage.set('userInfo', {})
uni.$storage.set('noSignInUuid', '')
uni.hideLoading()
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
uni.$logger.local.warn(`跳转登录页:currentPage:${currentPage.route}`)
if (currentPage.route != 'pages/common/login') {
uni.reLaunch({
url: '/pages/common/login'
})
}
reject('登录已过期,请重新登录')
}
}
export default new Request()