wanshenmean
2025-04-08 6d0ee85a6c0522f11036ec8c17c3dcb7ac8495da
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
let baseUrl = 'http://192.168.0.191:9291'
const install = (Vue, vm) => {
 
    // 此为自定义配置参数,具体参数见上方说明
    Vue.prototype.$u.http.setConfig({
        baseUrl: baseUrl,
        loadingText: '努力加载中~',
        loadingTime: 5000,
        originalData: true,
        // ......
    });
 
    // 请求拦截,配置Token等参数
    Vue.prototype.$u.http.interceptor.request = (config) => {
        // 判断是否为完整 URL,如果是则不使用 baseUrl
        if (config.url.includes('http://') || config.url.includes('https://')) {
            config.baseURL = '';
        } else {
            config.baseURL = baseUrl;
        }
 
        config.header.Token = 'xxxxxx';
        config.header.Authorization = "Bearer " + uni.getStorageSync('jo_id_token');
        // 可以对某个url进行特别处理,此url参数为this.$u.get(url)中的url值 
        if (config.url == '/api/User/login') config.header.noToken = true;
        // 最后需要将config进行return
        return config;
        // 如果return一个false值,则会取消本次请求
        // if(config.url == '/user/rest') return false; // 取消某次请求
    }
 
    // 响应拦截,判断状态码是否通过
    Vue.prototype.$u.http.interceptor.response = (res) => {
        if (res.statusCode == 200) {
            // res为服务端返回值,可能有code,result等字段
            // 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
            // 如果配置了originalData为true,请留意这里的返回值
            return res.data;
        } else if (res.statusCode == 401) {
            // 假设201为token失效,这里跳转登录
            vm.$u.toast('验证失败,请重新登录');
            setTimeout(() => {
                // 此为uView的方法,详见路由相关文档
                vm.$u.route('/pages/login/login')
            }, 1500)
            return false;
        } else if (res.statusCode == 202) {
            // 如果返回false,则会调用Promise的reject回调,
            // 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
            vm.$u.post("/api/User/replaceToken").then(res => {
                if (x.data.status) {
                    vm.$u.vuex('vuex_token', x.data.data)
                    vm.$u.route({
                        type: "navigateBack",
                        delta: -1
                    })
                } else {
                    console.log(x.data.message);
                    vm.$u.toast('验证过期,请重新登录');
                    setTimeout(() => {
                        // 此为uView的方法,详见路由相关文档
                        vm.$u.route('/pages/login/login')
                    }, 1500)
                }
            }).catch(err => {
                uni.reLaunch({
                    url: '/pages/login/login'
                });
            })
            // return false; // return false后不再进入then回调,但会进入catch回调
            return false;
        }
    }
}
 
export default {
    install,
    baseUrl
}