purchase-let/utils/request.js

96 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-04-25 18:02:30 +08:00
import {
2024-06-17 15:29:52 +08:00
config
2024-04-25 18:02:30 +08:00
} from '@/config/app';
import useUserStore from '@/store/user';
const userStore = useUserStore();
function baseRequest(url, method, data, {
2024-06-17 15:29:52 +08:00
noAuth = false,
noVerify = false,
onReLogin = false
2024-04-25 18:02:30 +08:00
}) {
2024-06-17 15:29:52 +08:00
let Url = config.HTTP_REQUEST_URL,
header = config.HEADER;
if (userStore.userInfo) {
header.TOKEN = userStore.token
}
2024-04-25 18:02:30 +08:00
2024-06-17 15:29:52 +08:00
return new Promise((reslove, reject) => {
uni.request({
url: Url + '/api' + url,
method: method || 'GET',
header: {
accept:'json',
2024-06-17 15:29:52 +08:00
...header
},
data: method != 'GET' ? data || {} : {},
params: method == 'GET' ? data : {},
success: (res) => {
// console.log(res, 'res')
2024-05-13 18:05:23 +08:00
2024-06-17 15:29:52 +08:00
if (res.data.show) {
uni.showToast({
title: res.data.msg || '操作成功',
icon: 'none',
})
}
if (noVerify)
reslove(res.data);
else if (res.data.code == -1) {
if (res.data.msg == "登录超时,请重新登录" && !noAuth) {
userStore.setToken('');
userStore.setUserInfo({});
uni.showModal({
content: '您需要先登录才可使用该功能, 是否前去登录',
success: (e) => {
if (e.confirm) uni.navigateTo({
url: '/pages/login/login'
})
}
})
}
} else if (res.data.code == 0) {
if (res.data.msg == "请求参数缺token" && !noAuth) {
userStore.setToken('');
userStore.setUserInfo({});
uni.showModal({
content: '您需要先登录才可使用该功能, 是否前去登录',
success: (e) => {
if (e.confirm) uni.navigateTo({
url: '/pages/login/login'
})
}
})
}
reject(res.data);
} 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('请求失败');
}
})
});
2024-04-25 18:02:30 +08:00
}
const syhttp = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
2024-06-17 15:29:52 +08:00
syhttp[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
2024-04-25 18:02:30 +08:00
});
export default syhttp;