react-taro小程序fetch网络请求封装


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;

​
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web_icon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值