无所不能的uniapp拦截器

无所不能的uniapp拦截器-uni.addInterceptor

拦截器能做什么?

uni.addInterceptoruni-app 框架中的一个 API,用于为特定的异步 API 方法添加拦截器。拦截器可以在方法执行前或执行后插入自定义逻辑,比如权限校验、日志记录、数据预处理等。 附上官方文档链接

参数名 类型 必填 默认值 说明 平台差异说明
invoke Function 拦截前触发
returnValue Function 方法调用后触发,处理返回值
success Function 成功回调拦截
fail Function 失败回调拦截
complete Function 完成回调拦截

项目实战

  • uni.request拦截器
  • 登录校验拦截器
  • uni.setStorage数据预处理
  • 隐私权限判断、引导

uni.request拦截器

ts 复制代码
const BASE_URL = 'https://www.example.com/'

const httpInterceptor: UniNamespace.InterceptorOptions = {
  invoke(args) {
    // request 触发前拼接 url
    args.url = BASE_URL + args.url
  },
  success(result) {
    console.log('interceptor-success',result)
    // 请求成功,但接口报错等情况上报
    if(result.data.code === xxx){
        errorReport(result.data.msg)
    }
  },
  fail(err) {
    console.log('interceptor-fail',err)
    // 请求失败等情况上报
    errorReport()
  },
  complete(res) {
    console.log('interceptor-complete',res)
  }
}
// 进行错误上报
function errorReport(errMsg?: string){
    uni.showToast({
      icon: "none",
      title: errMsg || "网络错误,换个网络试试",
    });
    customReport({
        msg: 'xxxx'
    })
}
ts 复制代码
export const requestInterceptor = {
  install() {
    // 拦截 request 请求
    uni.addInterceptor("request", httpInterceptor);
    // 拦截 uploadFile 文件上传
    uni.addInterceptor("uploadFile", httpInterceptor);
  },
};

登录校验拦截器

ts 复制代码
const loginRoute = "/pages/login/index";

let needLoginPages: string[] = [
 "/pages/order/index",
];

/**
* 判断是否登录
*/
export function isLogged(): boolean {
 return false;
}

// 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
const navigateToInterceptor: UniNamespace.InterceptorOptions = {
 // 注意,这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
 invoke({ url }: { url: string }) {
   // console.log(url) 
   const path = url.split("?")[0];
   const isNeedLogin = needLoginPages.includes(path);
   if (!isNeedLogin) {
     return true;
   }
   const hasLogin = isLogged();
   if (hasLogin) {
     return true;
   }
   goLogin(url);
   return false;
 },
};

function goLogin(redirect: string = "") {
 uni.navigateTo({
   url: `${loginRoute}?redirect=${encodeURIComponent(redirect)}`,
 });
}

export const routeInterceptor = {
 install() {
   uni.addInterceptor("navigateTo", navigateToInterceptor);
   uni.addInterceptor("reLaunch", navigateToInterceptor);
   uni.addInterceptor("redirectTo", navigateToInterceptor);
   uni.addInterceptor("switchTab", navigateToInterceptor);
 },
};

uni.setStorage数据预处理

ts 复制代码
// 这是个数据处理函数
function processingData(){
}

const storage: UniNamespace.InterceptorOptions = {
  invoke(args) {
    console.log('存储数据前:', args);
    args.data = processingData(args.data); 
    console.log('处理后的数据:', args.data);
  },
  success() {
    console.log('数据存储成功');
  },
  fail(err) {
    console.error('数据存储失败:', err);
  }
}
ts 复制代码
export const storageInterceptor = {
  install() {
    uni.addInterceptor("setStorage", storage);
  },
};
借助拦截器修复快手小程序平台的一个bug
ts 复制代码
const setStorageInterceptor: UniNamespace.InterceptorOptions = {
  invoke(args: { data: any }) {
    // console.log(args, "========args=======");
    // #ifdef MP-KUAISHOU
    args.data = JSON.parse(JSON.stringify(args.data));
    // #endif
  },
  success(args) {
    // console.log(args, "========success=======");
  },
  fail(err) {
    // console.log(err, "========fail=======");
  },
};
/**
 * 解决快手小程序setStorage不支持proxy对象的问题
 * */
export const KuaiShouSetStorageProxyFixInterceptor = {
  install() {
    // 拦截 setStorage
    uni.addInterceptor("setStorage", setStorageInterceptor);
  },
};

隐私权限判断、引导

开发中......

相关推荐
NiceCloud喜云2 分钟前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby32 分钟前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩35 分钟前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
Front思2 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫4 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。4 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星5 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒5 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端
丷丩5 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
Mr.Daozhi5 小时前
RAG 进阶实战:跑通 Demo 后我连续翻了 6 次车,逐一修复才真正可用(含 Gradio Web 版)
前端·数据库·langchain·大模型·gradio·rag·科研工具