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.

78 lines
1.8 KiB
JavaScript

// http.js
import { ref } from 'vue';
// 封装请求拦截器
function requestInterceptor(options) {
// 在请求发送之前做一些处理
// 比如添加请求头、修改请求参数等
options.header = {
'Authorization': 'Bearer ' + uni.getStorageSync("access_token"), // 假设需要添加 token
'Content-Type': 'application/json' // 设置请求头
};
return options;
}
// 封装响应拦截器
function responseInterceptor(response) {
// 对响应数据进行处理
// 比如根据响应状态码进行不同的操作
if (response.statusCode === 200) {
// 请求成功
if(response.data.status==false){
uni.showToast({
title: response.data.msg ,
icon: 'none'
});
}
return response.data;
} else {
// 请求失败
uni.showToast({
title: '请求失败,请稍后重试',
icon: 'none'
});
return Promise.reject(response.data);
}
}
// 发送请求的方法,内部使用拦截器
export function useHttp() {
const isLoading = ref(false);
function sendRequest(options) {
// 请求发送之前,先经过请求拦截器处理
let processedOptions = requestInterceptor(options);
isLoading.value = true;
uni.showLoading({
title: '加载中',
mask:true
});
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();
reject(err);
}
});
});
}
return {
isLoading,
sendRequest
};
}