purchase-let/utils/request.js

76 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-04-25 18:02:30 +08:00
import {
config
} from '@/config/app';
import useUserStore from '@/store/user';
const userStore = useUserStore();
function baseRequest(url, method, data, {
noAuth = false,
noVerify = false,
onReLogin = false
}) {
let Url = config.HTTP_REQUEST_URL,
header = config.HEADER;
if (userStore.userInfo) {
header.TOKEN = userStore.token
}
return new Promise((reslove, reject) => {
uni.request({
2024-04-28 18:08:57 +08:00
url: Url + '/api' + url,
2024-04-25 18:02:30 +08:00
method: method || 'GET',
header: {
...header
},
data: method != 'GET' ? data || {} : {},
params: method == 'GET' ? data : {},
success: (res) => {
if (res.data.show) {
uni.showToast({
title: res.data.msg || '操作成功',
2024-04-30 16:24:55 +08:00
icon: 'none',
2024-04-25 18:02:30 +08:00
})
}
if (noVerify)
reslove(res.data);
else if (res.data.code == -1) {
if (res.data.msg == "登录超时,请重新登录") {
2024-05-06 14:26:18 +08:00
userStore.setToken('');
userStore.setUserInfo({});
2024-04-25 18:02:30 +08:00
uni.reLaunch({
2024-05-06 14:26:18 +08:00
url: '/pages/login/login'
2024-04-25 18:02:30 +08:00
})
}
} else if (res.data.code == 0) {
2024-04-30 18:08:36 +08:00
reject(res.data);
2024-04-25 18:02:30 +08:00
} else if (res.data.code == 1) {
reslove(res.data);
} else if (res.data.code == 200) {
reslove(res.data.data);
} else if ([410000, 410001, 410002, 40000].indexOf(res.data.code) !== -1) {
reject(res.data);
} else if (res.data.code == 501) {
reject(res.data);
} else {
reject(res.data.msg || '请检查网络');
}
},
fail: (message) => {
console.log(message, '错误')
uni.showToast({
title: '网络错误',
icon: 'none'
})
reject('请求失败');
}
})
});
}
const syhttp = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
syhttp[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});
export default syhttp;