You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
2.4 KiB
JavaScript
88 lines
2.4 KiB
JavaScript
import { ref } from 'vue';
|
|
|
|
function requestInterceptor(options) {
|
|
const token = uni.getStorageSync("access_token");
|
|
|
|
options.header = {
|
|
'Authorization': token ? 'Bearer ' + token : '',
|
|
'Content-Type': 'application/json'
|
|
};
|
|
return options;
|
|
}
|
|
|
|
function responseInterceptor(response) {
|
|
if (response.statusCode === 200) {
|
|
const data = response.data;
|
|
|
|
if (data.status === 'Toke_Error' || data.code === 10001) {
|
|
uni.removeStorageSync("access_token");
|
|
uni.removeStorageSync("refresh_token");
|
|
|
|
uni.showModal({
|
|
title: '提示',
|
|
content: '登录已过期,请重新登录',
|
|
showCancel: false,
|
|
success: () => {
|
|
uni.reLaunch({
|
|
url: '/pages/Login'
|
|
});
|
|
}
|
|
});
|
|
return Promise.reject(data);
|
|
}
|
|
|
|
if (data.status === false) {
|
|
uni.showToast({
|
|
title: data.msg || data.meg || '操作失败',
|
|
icon: 'none'
|
|
});
|
|
}
|
|
|
|
return data;
|
|
} else {
|
|
uni.showToast({
|
|
title: '请求失败,请稍后重试',
|
|
icon: 'none'
|
|
});
|
|
return Promise.reject(response.data);
|
|
}
|
|
}
|
|
|
|
export function useHttp() {
|
|
const isLoading = ref(false);
|
|
|
|
function sendRequest(options) {
|
|
isLoading.value = true;
|
|
uni.showLoading({
|
|
title: '加载中'
|
|
});
|
|
|
|
let processedOptions = requestInterceptor(options);
|
|
|
|
return new Promise((resolve, reject) => {
|
|
uni.request({
|
|
...processedOptions,
|
|
success: (res) => {
|
|
let processedResponse = responseInterceptor(res);
|
|
isLoading.value = false;
|
|
uni.hideLoading();
|
|
resolve(processedResponse);
|
|
},
|
|
fail: (err) => {
|
|
isLoading.value = false;
|
|
uni.hideLoading();
|
|
uni.showToast({
|
|
title: '网络异常,请检查网络',
|
|
icon: 'none'
|
|
});
|
|
reject(err);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
return {
|
|
isLoading,
|
|
sendRequest
|
|
};
|
|
} |