import Taro from '@tarojs/taro'
const CODE_SUCCESS = 200
const CODE_FORBIDDEN = 403
const BASE_URL = '请求域名'
const ERROR_MSG_MAP = {
[CODE_FORBIDDEN]: '未登录',
default: '请求异常'
}
let loadingCount = 0
function showLoading() {
if (loadingCount === 0) {
Taro.showLoading({
title: "加载中",
mask: true,
})
}
loadingCount++
}
function hideLoading() {
if (loadingCount <= 0) {
return;
}
loadingCount--;
if (loadingCount === 0) {
Taro.hideLoading();
}
}
function getStorage(key) {
return Taro.getStorage({
key
})
.then((res) => res.data)
.catch(() => '')
}
async function fetch(options) {
const {
url,
method = "GET",
showToast = false,
autoLogin = false,
leaveMeAlone = false,
data
} = options;
let token = "";
try {
const result = await getStorage('X-Auth-Token');
token = result || "";
} catch (error) {
console.log(error);
}
let header = {
};
if (token !== "") {
header['X-Auth-Token'] = token;
}
if (method === "POST") {
header['content-type'] = "application/json";
} else if (method === "PUT") {
header['content-type'] = "application/x-www-form-urlencoded;charset=UTF-8";
}
let addr = "";
if (leaveMeAlone) {
addr = url;
} else {
addr = `${BASE_URL}${url}`;
}
try {
showLoading();
let response = {};
if (url === '上传') {
response = await Taro.uploadFile({
url: addr,
filePath: data.path,
name: 'file',
formData: {
photoTime: data.time,
},
header: {
WX_UID: '',
Authorization: token,
...header,
}
});
} else {
response = await Taro.request({
url: addr,
method,
data,
headers: {
...header
},
});
}
hideLoading();
//处理错误情况
const {
statusCode
} = response;
if (statusCode !== CODE_SUCCESS) {
throw new Error(ERROR_MSG_MAP[statusCode] || ERROR_MSG_MAP.default)
}
//处理返回结果中status不为success的情况
const responseData = response.data || {};
if (responseData.status && responseData.status !== CODE_SUCCESS) {
throw new Error(responseData.message || ERROR_MSG_MAP.default)
}
//处理返回结果中code不为200或500的情况
if (responseData.code && (responseData.code !== CODE_SUCCESS && responseData.code !== 500)) {
throw new Error(responseData.message || ERROR_MSG_MAP.default)
}
//处理get请求没有数据时的情况
if (method === 'GET' && !responseData.data) {
throw new Error('暂无数据')
}
return responseData;
} catch (error) {
hideLoading();
//统一进行错误提示和抛出异常信息给上层调用者
if (showToast) {
let message = '';
if (typeof error === Object && error.hasOwnProperty('message')) {
message = error.message;
} else {
message = '网络出错,请稍后再试!';
}
Taro.showToast({
title: message,
icon: "none",
duration: 3000,
})
}
throw new Error(error);
}
}
export default fetch;
06-18
1100
03-23
1330
05-17
1728
06-28
2285