interceptor.md 1.3 KB
Newer Older
1 2
### uni.addInterceptor(STRING, OBJECT)
添加拦截器
M
mehaotian 已提交
3 4 5 6

**STRING 参数说明**

需要拦截的`api`名称,如:`uni.addInterceptor('request', OBJECT)` ,将拦截 `uni.request()`
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

**OBJECT 参数说明**

|参数名		|类型			|必填	|默认值	|说明					|平台差异说明	|
|:-				|:-				|:-		|:-			|:-						|:-						|
|invoke		|Function	|否		|				|拦截前触发		|							|
|success	|Function	|否		|				|成功回调拦截	|							|
|fail			|Function	|否		|				|失败回调拦截	|							|
|complete	|Function	|否		|				|完成回调拦截	|							|


**示例**

```javascript
uni.request({
    url: 'request/login', //仅为示例,并非真实接口地址。
    success: (res) => {
M
mehaotian 已提交
24
        console.log(res.data);
25 26
        // 打印: {code:1,...}
    }
M
mehaotian 已提交
27 28 29
});


30
uni.addInterceptor('request', {
M
mehaotian 已提交
31 32
  invoke(args) {
    // request 触发前拼接 url 
33 34
    args.url = 'https://www.example.com/'+args.url
  },
M
mehaotian 已提交
35 36 37
  success(args) {
    // 请求成功后,修改code值为1
    args.data.code = 1
38
  }, 
M
mehaotian 已提交
39 40
  fail(err) {
    console.log('interceptor-fail',err)
41
  }, 
M
mehaotian 已提交
42 43
  complete(res) {
    console.log('interceptor-complete',res)
44
  }
M
mehaotian 已提交
45 46
})

47
```
M
mehaotian 已提交
48 49 50 51 52 53 54

### uni.removeInterceptor(STRING)
删除拦截器

**STRING 参数说明**

需要删除拦截器的`api`名称
55 56 57 58

**示例**

```javascript
M
mehaotian 已提交
59 60 61 62

uni.removeInterceptor('request')

```