初始化
This commit is contained in:
85
common/js/request.js
Normal file
85
common/js/request.js
Normal file
@@ -0,0 +1,85 @@
|
||||
|
||||
import config from "./config";
|
||||
let arr = []
|
||||
export default (options = {}) => {
|
||||
if (options.data == undefined) {
|
||||
options.data = {}
|
||||
}
|
||||
// 防止接口重复点击
|
||||
if (arr.indexOf(options.url) === -1) {
|
||||
arr.push(options.url)
|
||||
} else {
|
||||
return new Promise((resolve, reject) => {
|
||||
reject({
|
||||
code: -1,
|
||||
msg: '请勿重复提交'
|
||||
})
|
||||
})
|
||||
}
|
||||
return new Promise((reslove, reject) => {
|
||||
uni.request({
|
||||
url: options.url.indexOf('http') === -1 ? config.domain + options.url : options.url,
|
||||
data: {
|
||||
...options.data,
|
||||
},
|
||||
header: {
|
||||
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
'Authorization': uni.getStorageSync('Authorization'),
|
||||
'Cookie': uni.getStorageSync('Cookie'),
|
||||
...options.header
|
||||
},
|
||||
method: options.method || 'GET',
|
||||
success: async (res) => {
|
||||
console.warn(res);
|
||||
if (options.url.indexOf('/org/login/valid') > -1) {
|
||||
uni.setStorageSync('Cookie', res.header['Set-Cookie']);
|
||||
}
|
||||
if (arr.indexOf(options.url) > -1) {
|
||||
arr.splice(arr.indexOf(options.url), 1)
|
||||
}
|
||||
if (res.data.isOk === false) {
|
||||
reject(res.data)
|
||||
errHandler(res.data)
|
||||
} else {
|
||||
reslove(res.data)
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
if (arr.indexOf(options.url) > -1) {
|
||||
arr.splice(arr.indexOf(options.url), 1)
|
||||
}
|
||||
reject(err)
|
||||
uni.showToast({
|
||||
icon: 'none',
|
||||
title: '网络异常,请稍后再试',
|
||||
})
|
||||
uni.reLaunch({
|
||||
url: '/pages/login/login',
|
||||
});
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误处理
|
||||
* @param {Number} code 错误码
|
||||
*/
|
||||
function errHandler (res) {
|
||||
switch (res.code) {
|
||||
case '401':
|
||||
// #ifdef MP
|
||||
uni.removeStorageSync('Cookie');
|
||||
uni.clearStorageSync();
|
||||
// #endif
|
||||
uni.reLaunch({ url: '/pages/login/login' })
|
||||
break
|
||||
default:
|
||||
uni.showToast({
|
||||
title: res.msg || '服务端未知错误',
|
||||
duration: 2000,
|
||||
icon: 'none'
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user