You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
108 lines
2.9 KiB
108 lines
2.9 KiB
import Taro from '@tarojs/taro';
|
|
import cookie from 'cookie';
|
|
import environment from '../config';
|
|
import { getState } from '../store/globalState';
|
|
|
|
const { baseUrl, errorHandle, loadingHandle } = environment;
|
|
|
|
//当前请求个数
|
|
let requestingNumber = 0;
|
|
|
|
// request拦截器
|
|
function requestBuilder(method, url, data, config) {
|
|
if (url.indexOf('token') == -1) {
|
|
let token = getState('token') || Taro.getStorageSync('token');
|
|
if (token) {
|
|
url += url.indexOf('?') == -1 ? '?' : '&';
|
|
url += `token=${token}`;
|
|
}
|
|
}
|
|
if (url.indexOf('http') != 0) {
|
|
url = baseUrl + url;
|
|
}
|
|
//通过config配置项控制跳过全局控制的loading显示
|
|
let isShowLoading = true;
|
|
let isShowErrorToast = true;
|
|
if (config) {
|
|
if (config.hideLoading) {
|
|
isShowLoading = false;
|
|
}
|
|
if (config.hideErrorToast) {
|
|
isShowErrorToast = false;
|
|
}
|
|
}
|
|
/*
|
|
同时触发两种加载状态
|
|
并发多个请求时showLoading会在使用showToast时提前结束
|
|
所以如果有多个并发请求,完成提示最好使用自定义的提示框而不是微信的
|
|
*/
|
|
if (loadingHandle && isShowLoading) {
|
|
Taro.showLoading({
|
|
title: '加载中...',
|
|
icon: 'none',
|
|
mask: true
|
|
});
|
|
Taro.showNavigationBarLoading();
|
|
}
|
|
requestingNumber++;
|
|
//请求结果处理
|
|
function dealRequest() {
|
|
requestingNumber--;
|
|
if (requestingNumber === 0 && loadingHandle && isShowLoading) {
|
|
Taro.hideLoading();
|
|
Taro.hideNavigationBarLoading();
|
|
}
|
|
}
|
|
//异常处理
|
|
function dealError(errorInfo) {
|
|
if (errorInfo && errorHandle && isShowErrorToast) {
|
|
Taro.showToast({
|
|
title: errorInfo,
|
|
icon: 'none',
|
|
duration: 1500
|
|
});
|
|
}
|
|
}
|
|
//给所有请求添加自定义header
|
|
let userCookie = Taro.getStorageSync('cookie');
|
|
let requestObj = {...config,url,method,data};
|
|
if (userCookie) {
|
|
requestObj.header= {
|
|
cookie: cookie.serialize('fsiota', userCookie.fsiota) + ';' + cookie.serialize('fsiota.sig', userCookie.sig)
|
|
}
|
|
}
|
|
return new Promise((resolved, rejected) => {
|
|
Taro.request(requestObj).then(res => {
|
|
dealRequest();
|
|
if (res.statusCode == 401) {
|
|
Taro.clearStorageSync();
|
|
Taro.reLaunch({
|
|
url: '/pages/auth/login/login'
|
|
});
|
|
}
|
|
if (res.statusCode !== 200 && res.statusCode !== 204) {
|
|
dealError(res.data.message || '请求出错');
|
|
}
|
|
resolved(res);
|
|
}).catch(err => {
|
|
dealRequest();
|
|
dealError('网络异常');
|
|
rejected(err);
|
|
});
|
|
});
|
|
|
|
}
|
|
export default {
|
|
get: function (url, data, config) {
|
|
return requestBuilder('GET', url, data, config);
|
|
},
|
|
post: (url, data, config ) => {
|
|
return requestBuilder('POST', url, data, config);
|
|
},
|
|
put: (url, data, config = {} ) => {
|
|
return requestBuilder('PUT', url, data, config);
|
|
},
|
|
del: (url, data, config) => {
|
|
return requestBuilder('DELETE', url, data, config);
|
|
}
|
|
};
|
|
|