朱桂飞
2023-03-22 4434c41562f18959967a957f09c795f0c24f3b70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
var Fly = require("./wx.umd.min")
var fly = new Fly
 
 
fly.config.loading = true;
//实例级配置
//fly.config.timeout=6000;
//添加拦截器
fly.interceptors.request.use((config, promise) => {
    console.info(fly.config.loading)
    if (fly.config.loading) {
        uni.showLoading({
            title: '加载中'
        });
    }
 
    //给所有请求添加自定义header
    //let token = getApp().globalData.token
    const token =  uni.getStorageSync('token');
    const userinfo =  uni.getStorageSync('userinfo');
    if (token) {
        config.headers["X-Access-Token"] = token;
        
        if(userinfo)
        config.headers["X-Tenant-Id"] = userinfo.loginTenantId;
    }else{
        jumpToLogin();
    }
    console.log('========================================== ')
    console.log('==    请求数据:' + JSON.stringify(config))
    console.log('=========================================== ')
    return config;
})
 
//添加响应拦截器,响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
    (response) => {
 
        console.log('========================================')
        console.log('==    响应数据:' + JSON.stringify(response.request.url))
        console.log('==    ' + JSON.stringify(response.data))
        console.log('======================================== ')
 
        //只将请求结果的data字段返回
 
        //TODO 处理没有token
        // jumpToLogin();
        uni.hideLoading()
        return response.data
    },
    (err) => {
        console.info(err)
        uni.hideLoading()
        //登录超时,重新登录
        if (err.response.status == 401) {
            jumpToLogin();
        }
        //发生网络错误后会走到这里
        //return Promise.resolve("ssss")
    }
)
 
 
 
//跳转到登录页
function jumpToLogin() {
    console.log('关闭所有页面跳转到login')
    uni.reLaunch({
        url: '/pages/login/login'
    });
}
 
module.exports = {
    fly
}