zhuguifei
昨天 7941623b1fb108a154ea4270d7c7e2df6031f6e5
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var Fly = require("./wx.umd.min")
var fly = new Fly
const log = false
 
 
fly.config.loading = true;
//实例级配置
fly.config.timeout=10000;
//添加拦截器
fly.interceptors.request.use((config, promise) => {
    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;
    }
    if(log){
        console.log('========================================== ')
        console.log('==    请求数据:' + JSON.stringify(config))
        console.log('=========================================== ')
    }
    return config;
})
 
//添加响应拦截器,响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
    (response) => {
 
        if(log){
            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 && err.response.status == 401) {
            uni.showToast({
                title: "登录状态已失效,重新登录!",
                icon: 'none',
                mask: true,
                complete: function(res) {
                    setTimeout(() => {
                        jumpToLogin();
                    }, 1000)
 
                },
            });
 
        } else {
            uni.showToast({
                title: '网络错误,请稍后重试~',
                icon: 'none',
                mask: true
            });
        }
        //发生网络错误后会走到这里
        //return Promise.resolve("ssss")
    }
)
 
 
 
//跳转到登录页
function jumpToLogin() {
    console.log('关闭所有页面跳转到login')
    uni.reLaunch({
        url: '/pages/login/login'
    });
}
 
module.exports = {
    fly
}