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

88 lines
2.5 KiB
JavaScript
Raw Normal View History

2023-04-04 08:47:19 +08:00
import config from './config';
let arr = [];
2023-01-11 16:33:13 +08:00
export default (options = {}) => {
if (options.data == undefined) {
2023-04-04 08:47:19 +08:00
options.data = {};
2023-01-11 16:33:13 +08:00
}
// 防止接口重复点击
if (arr.indexOf(options.url) === -1) {
2023-04-04 08:47:19 +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-01-11 16:33:13 +08:00
}
return new Promise((reslove, reject) => {
uni.request({
2023-04-04 08:47:19 +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',
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
2023-04-04 08:47:19 +08:00
Authorization: '12',
...options.header,
2023-01-11 16:33:13 +08:00
},
method: options.method || 'GET',
success: async (res) => {
2023-03-30 09:04:07 +08:00
console.log(res);
2023-01-11 16:33:13 +08:00
if (arr.indexOf(options.url) > -1) {
2023-04-04 08:47:19 +08:00
arr.splice(arr.indexOf(options.url), 1);
2023-01-11 16:33:13 +08:00
}
2023-04-04 08:47:19 +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-04-04 08:47:19 +08:00
reslove(res.data);
2023-01-11 16:33:13 +08:00
}
},
fail: (err) => {
if (arr.indexOf(options.url) > -1) {
2023-04-04 08:47:19 +08:00
arr.splice(arr.indexOf(options.url), 1);
2023-01-11 16:33:13 +08:00
}
2023-04-04 08:47:19 +08:00
reject(err);
2023-01-11 16:33:13 +08:00
uni.showToast({
icon: 'none',
title: '网络异常,请稍后再试',
2023-04-04 08:47:19 +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-01-11 16:33:13 +08:00
});
},
2023-04-04 08:47:19 +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-03-16 15:26:25 +08:00
switch (res.resultCode) {
2023-01-11 16:33:13 +08:00
case '401':
// #ifdef MP
uni.removeStorageSync('Cookie');
uni.clearStorageSync();
// #endif
2023-04-04 08:47:19 +08:00
uni.reLaunch({ url: '/pages/user/login' });
break;
2023-01-11 16:33:13 +08:00
default:
uni.showToast({
title: res.msg || '服务端未知错误',
duration: 2000,
2023-04-04 08:47:19 +08:00
icon: 'none',
2023-01-11 16:33:13 +08:00
});
break;
}
}