# uni.addInterceptor(STRING, OBJECT)

Add interceptor

# addInterceptor 兼容性

HarmonyOS
HBuilderX 4.23

STRING parameter description

Name of the api that needs to be intercepted, such as uni.addInterceptor('request', OBJECT), which will intercept uni.request()

注意:

  • 仅支持异步接口,如:uni.setStorage(OBJECT),暂不支持同步接口如:uni.setStorageSync(KEY,DATA)
  • uniCloud请求云端接口时(callFunction、uploadFile等)也会使用uni.request发送请求,请确保拦截器内不错误的处理此类请求

OBJECT parameter description

Parameter Name Type Required Default Value Description Platform Difference Description
invoke Function 拦截前触发
returnValue Function 方法调用后触发,处理返回值
success Function No Success callback interception
fail Function No Fail callback interception
complete Function No Complete callback interception

Example

uni.request({
    success: (res) => {
        console.log(res.data);
        //Print: {code:1,...}
    }
});


uni.addInterceptor('request', {
  invoke(args) {
    // request 触发前拼接 url
    args.url = 'https://www.example.com/'+args.url
  },
  success(args) {
    //After a successful request, modify the code value to 1
    args.data.code = 1
  },
  fail(err) {
    console.log('interceptor-fail',err)
  },
  complete(res) {
    console.log('interceptor-complete',res)
  }
})

uni.addInterceptor({
  returnValue(args) {
    // 只返回 data 字段
    return args.data
  }
})

# uni.removeInterceptor(STRING)

Remove interceptor

# removeInterceptor 兼容性

HarmonyOS
HBuilderX 4.23

STRING parameter description

Name of api that needs to delete the interceptor

Example


uni.removeInterceptor('request')

Note: Intercepting uni.switchTab itself has no problem. But the underlying logic of clicking tabbar on the WeChat applet is not to trigger uni.switchTab. So it is misunderstood that the interception is invalid, and the solution for such scenarios is to handle it in the page life cycle onShow of the tabbar page.

# 拦截器的适用场景非常多,比如路由拦截,权限引导等。

你可以参考插件市场,拦截器应用示例:图片选择api时无权限,引导用户快捷打开系统设置:https://ext.dcloud.net.cn/plugin?id=5095