1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| import Taro from '@tarojs/taro'; import { post } from '.';
export async function requestToken() { let token = Taro.getStorageSync('userToken') || '';
if (!token) { const appid = Taro.getAccountInfoSync().miniProgram.appId; const { code } = await Taro.login();
const { data: { data }, } = await post(`user/wxLogin?code=${code}&appId=${appid}`, {}, { isNeedToken: false });
Taro.setStorageSync('userToken', data); token = data; }
return token; }
async function requestInterceptor(request: Taro.RequestParams) { const { header, isNeedToken, isShowLoading } = request;
if (isShowLoading) Taro.showLoading({ title: '加载中', mask: true });
if (isNeedToken) request.header = { ...header, Authorization: await requestToken() };
return request; }
function responseInterceptor(request: Taro.RequestParams, response: Taro.request.SuccessCallbackResult) { const { isShowLoading, isShowFailToast, isThrowError } = request; const { statusCode, data, errMsg } = response;
isShowLoading && Taro.hideLoading();
if (statusCode === 200) { const { code, msg } = data;
if (code == 0) { return response; } else { if (isShowFailToast) Taro.showToast({ icon: 'none', title: msg || '未知错误,十分抱歉!', duration: 2000, mask: true });
if (isThrowError) throw new Error(`后端返回的错误信息-- ${msg}`);
return response; } } else { let title = '未知错误,万分抱歉!';
if (statusCode === -1) title = '网络请求失败,请检查您的网络。';
if (statusCode > 0) title = `url:${request.url.toString()}, statusCode:${response.statusCode}`;
if (statusCode == 401) { Taro.clearStorage(); Taro.reLaunch({ url: '/pages/home/index' }); }
if (isShowFailToast) Taro.showToast({ icon: 'none', title: title || errMsg, duration: 2000, mask: true });
throw new Error(`HTTP请求失败---- ${title || errMsg}`); } }
const interceptor = async function (chain: Taro.Chain) { const requestParams = chain.requestParams;
let req = await requestInterceptor(requestParams);
return chain.proceed(req).then((res: Taro.request.SuccessCallbackResult) => {
return responseInterceptor(req, res); }); };
export default interceptor;
|