Files
app-govern/common/js/request.js

88 lines
2.6 KiB
JavaScript
Raw Normal View History

2023-07-03 09:16:54 +08:00
import config from './config'
let arr = []
2023-01-11 16:33:13 +08:00
export default (options = {}) => {
if (options.data == undefined) {
2023-07-03 09:16:54 +08:00
options.data = {}
2023-01-11 16:33:13 +08:00
}
// 防止接口重复点击
if (arr.indexOf(options.url) === -1) {
2023-07-03 09:16:54 +08:00
arr.push(options.url)
2023-01-11 16:33:13 +08:00
} else {
return new Promise((resolve, reject) => {
reject({
code: -1,
2023-04-04 08:47:19 +08:00
msg: '请勿重复提交',
2023-07-03 09:16:54 +08:00
})
})
2023-01-11 16:33:13 +08:00
}
return new Promise((reslove, reject) => {
uni.request({
2023-07-03 09:16:54 +08:00
url: options.url.indexOf('http') === -1 ? config.domain + options.url : options.url,
2023-01-11 16:33:13 +08:00
data: {
...options.data,
},
header: {
2023-04-04 09:14:20 +08:00
// 'Content-Type': 'application/json;charset=UTF-8',
2023-07-03 09:16:54 +08:00
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
2023-07-03 20:29:24 +08:00
Authorization: uni.getStorageSync('access_token'),
2023-04-04 08:47:19 +08:00
...options.header,
2023-01-11 16:33:13 +08:00
},
method: options.method || 'GET',
success: async (res) => {
2023-07-03 09:16:54 +08:00
console.log(res)
2023-01-11 16:33:13 +08:00
if (arr.indexOf(options.url) > -1) {
2023-07-03 09:16:54 +08:00
arr.splice(arr.indexOf(options.url), 1)
2023-01-11 16:33:13 +08:00
}
2023-07-03 09:16:54 +08:00
if (res.data.resultCode !== 10000 && res.data.code !== 'A0000') {
errHandler(res.data)
reject(res.data)
2023-01-11 16:33:13 +08:00
} else {
2023-07-03 09:16:54 +08:00
reslove(res.data)
2023-01-11 16:33:13 +08:00
}
},
fail: (err) => {
if (arr.indexOf(options.url) > -1) {
2023-07-03 09:16:54 +08:00
arr.splice(arr.indexOf(options.url), 1)
2023-01-11 16:33:13 +08:00
}
2023-07-03 09:16:54 +08:00
reject(err)
2023-01-11 16:33:13 +08:00
uni.showToast({
icon: 'none',
title: '网络异常,请稍后再试',
2023-07-03 09:16:54 +08:00
})
2023-01-11 16:33:13 +08:00
uni.reLaunch({
2023-01-13 16:32:56 +08:00
url: '/pages/user/login',
2023-07-03 09:16:54 +08:00
})
2023-01-11 16:33:13 +08:00
},
2023-07-03 09:16:54 +08:00
})
})
}
2023-01-11 16:33:13 +08:00
/**
* 错误处理
* @param {Number} code 错误码
*/
2023-04-04 08:47:19 +08:00
function errHandler(res) {
2023-07-03 20:29:24 +08:00
switch (res.code) {
2023-01-11 16:33:13 +08:00
case '401':
// #ifdef MP
2023-07-03 20:29:24 +08:00
uni.clearStorageSync()
// #endif
uni.reLaunch({ url: '/pages/user/login' })
break
case 'A0202':
// #ifdef MP
2023-07-03 09:16:54 +08:00
uni.clearStorageSync()
2023-01-11 16:33:13 +08:00
// #endif
2023-07-03 09:16:54 +08:00
uni.reLaunch({ url: '/pages/user/login' })
break
2023-01-11 16:33:13 +08:00
default:
uni.showToast({
2023-07-03 20:29:24 +08:00
title: res.message || res.msg || '网络异常,请稍后再试',
2023-01-11 16:33:13 +08:00
duration: 2000,
2023-04-04 08:47:19 +08:00
icon: 'none',
2023-07-03 09:16:54 +08:00
})
break
2023-01-11 16:33:13 +08:00
}
}