zhangwei
2024-09-29 94384dcf5066aa1a7b2e37874fe331e148bc9249
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// 引入luch-request
import {
    http
} from '@/uni_modules/uview-plus'
import {
    apiBaseUrl
} from '@/common/setting/constVarsHelper.js';
import * as db from '@/common/utils/dbHelper.js' //引入common
//  初始化请求配置
const initRequest = (vm) => {
    http.setConfig((defaultConfig) => {
        /* defaultConfig 为默认全局配置 */
        defaultConfig.baseURL = apiBaseUrl; /* 根域名 */
        //defaultConfig.header = {
        //    'Content-type': 'application/json1'
        //};
        defaultConfig.method = 'POST';
        defaultConfig.dataType = 'json';
        // #ifndef MP-ALIPAY
        defaultConfig.responseType = 'text';
        // #endif
        // 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
        //defaultConfig.custom = {}; // 全局自定义参数默认值
        // #ifdef APP-PLUS || MP-ALIPAY || MP-WEIXIN
        defaultConfig.timeout = 60000;
        // #endif
        // #ifdef APP-PLUS
        defaultConfig.sslVerify = true;
        // #endif
        // #ifdef APP-PLUS
        defaultConfig.firstIpv4 = false; // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
        // #endif
        // 局部优先级高于全局,返回当前请求的task,options。请勿在此处修改options。非必填
        // getTask: (task, options) => {
        // 相当于设置了请求超时时间500ms
        //   setTimeout(() => {
        //     task.abort()
        //   }, 500)
        // },
        // 全局自定义验证器。参数为statusCode 且必存在,不用判断空情况。
        defaultConfig.validateStatus = (statusCode) => { // statusCode 必存在。此处示例为全局默认配置
            return statusCode >= 200 && statusCode < 501
        }
 
        return defaultConfig
    })
 
    // 请求拦截
    http.interceptors.request.use((config) => { // 可使用async await 做异步操作
        // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
        config.data = config.data || {}
        if (config?.custom?.needToken) {
            // 获取用户token
            const userToken = db.get("userToken");
            if (!userToken) {
                console.log("开启弹窗",vm.$store);
                // vm.$store.commit('showLoginTip', true);
                //console.log("弹窗已经开启");
                // return false;
            } else {
                config.header.Authorization = 'Bearer ' + userToken;
            }
            console.log(config, config?.custom?.needToken, 'config?.custom?.needToken');
        }
        //额外需求
        if (config.custom.methodName == 'user.share' || config.custom.methodName == "pages.getpageconfig" ||
            config.custom.methodName == "goods.goodsList") {
            const userToken = db.get("userToken");
            config.header.Authorization = 'Bearer ' + userToken;
        }
 
        return config
    }, config => { // 可使用async await 做异步操作
        return Promise.reject(config)
    })
 
    // 响应拦截
    http.interceptors.response.use((response) => {
        /* 对响应成功做点什么 可使用async await 做异步操作*/
        console.log(response,'response,');
        const data = response.data
        if (response.statusCode == 200) {
            let pages = getCurrentPages();
            var page = pages[pages.length - 1];
 
            if (!data.status && page) {
                // 登录信息过期或者未登录
                if (data.data === 401 || data.data === 14006) {
                    // #ifdef APP-PLUS || APP-PLUS-NVUE
                    if (page.route.indexOf('pages/login/index') < 0) {
                        db.del("userToken");
                        uni.showToast({
                            title: result.msg,
                            icon: 'none',
                            duration: 1000,
                            complete: function() {
                                setTimeout(function() {
                                        uni.hideToast();
                                        uni.navigateTo({
                                            url: '/pages/login/index'
                                        });
                                    },
                                    1000);
                            }
                        });
                    }
                    // #endif
                    // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
                    db.del("userToken");
                    // vm.$store.commit('userInfo', null);
                    //console.log("开启登录弹窗");
                    // vm.$store.commit('hasLogin', false);
                    // #endif
                }
            }
        }else if(response.statusCode==401){
            db.del("userToken");
            uni.showToast({
                title: '登录失效,请重新登录!',
                icon: 'none',
                duration: 1000,
                complete: function() {
                    setTimeout(function() {
                            uni.hideToast();
                            uni.redirectTo({
                                url: '/pages/login/index'
                            });
                        },
                        1000);
                }
            });
        }
        return data === undefined ? {} : data
    }, (response) => {
        // 对响应错误做点什么 (statusCode !== 200)
        return Promise.reject(response)
    })
    // requestInterceptors()
    // responseInterceptors()
}
export {
    initRequest
}