# uni.addInterceptor(STRING, OBJECT)

Add interceptor

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({
    url: 'request/login', //仅为示例,并非真实接口地址。
    success: (res) => {
        console.log(res.data);
        //Print: {code:1,...}
    }
});


uni.addInterceptor('request', {
  invoke(args) {
    //Splice url before triggering request 
    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

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.

# Interceptors can be used in many scenarios including route interception, authority booting and so on.

You can refer to the plug-in market for an example of the application of the interceptor: the picture has no permission when selecting api, and guide the user to quickly open the system settings: https://ext.dcloud.net.cn/plugin?id=5095