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']
react-taro小程序fetch网络请求封装
于 2022-03-24 17:01:14 首次发布
本文介绍了如何使用Taro.js封装网络请求函数,注重处理登录状态和错误反馈,确保了在不同场景下的请求体验。通过getStorage和fetch函数,实现了自动登录和统一错误提示。

最低0.47元/天 解锁文章
451

被折叠的 条评论
为什么被折叠?



