Taro+VantUI请求拦截处理

请求拦截处理

备注: CONF.baseUrl需要在config->index.js文件中进行配置

代码如下:

    import Taro, { Chain } from "@tarojs/taro";
	const { brand } = Taro.getSystemInfoSync();
	const isDevTools = brand === "devtools";
	const IgnoreRoute =[CONF.baseUrl+'/api/user/login/'];
	
	/**
	 * 响应拦截器
	 * @param chain
	 * @returns
	 */
	const responseInterceptor = function (chain: Chain) {
	  const requestParams = chain.requestParams;
	
	  return chain.proceed(requestParams).then((res) => {
	    const {data} = res;
	    // 401身份验证失败
	    if(data.code === 401 && !IgnoreRoute.includes(requestParams.url)){
	      Taro.showToast({
	        title: data.message ,
	        icon: 'error',
	        success:()=>{
	          Taro.redirectTo({
	            url: `/pages/login/index`,
	          });
	        }
	      });
	    }
	    //服务器错误
	    if(data.code===500){
	      Taro.showToast({
	        title: data.message,
	        icon: 'error',
	      });
	    }
	    return res;
	  });
	};
	
	/**
	 * 业务拦截器
	 * 有来接口处理参数,data 统一 {b: string,sign: string, c: string}
	 * @param chain
	 * @returns
	 */
	const interceptor = function (chain: Chain) {
	  const { requestParams } = chain;
	  const { url = "", header } = requestParams;
	  const transferHeader = {
	    "content-type": "application/json",
	    ...header,
	    openid: Taro.getStorageSync("openId"),
	    Authorization: `LAIBAO ${Taro.getStorageSync(TOKEN)}`,
	  };
	  if (
	    ["/api"].find((route) =>
	      url.startsWith(route)
	    )
	  ) {
	    requestParams.header = { ...transferHeader };
	    requestParams.url = `${CONF.baseUrl}${url}`;
	    return chain.proceed(requestParams).then((res) => res);
	  }
	  return chain.proceed(requestParams).then((res) => res);
	};
	
	Taro.addInterceptor(interceptor);
	Taro.addInterceptor(responseInterceptor);
	
	
	export interface ResponseType<T> {
	  code: number;
	  msg: string;
	  data?: T;
	  runtime?: number;
	}
	
	export interface ErrorType {
	  errorCode: number;
	  errorMsg: string;
	}
	
	function httpRequest<T = any, U = any>(option: any): Promise<T> {
	  const start = +new Date();
	  return Taro.request<T, U>(option).then((res: any) => {
	    !isDevTools &&
	      console.log("request time", +new Date() - start, "ms", option?.url,CONF.baseUrl);
	    if (res) {
	      const { code, message } = res?.data;
	      if (code === 200) {
	        !isDevTools && console.warn(option, res.data);
	        return res.data as T;
	      }
	      return { code: code, message: message } as unknown as T;
	    } else {
	      return res as T;
	    }
	  });
	}
	
	export default httpRequest;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值