lefengyang
3 days ago a9c835459990db39ae2db5157d7ad835dcd25b44
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
// 此vm参数为页面的实例,可以通过它引用vuex中的变量
export const Request = (vm)=>{
    // 初始化请求配置
    uni.$uv.http.setConfig((config) => {
        /* config 为默认全局配置*/
        config.baseURL = 'https://shoujike.shenzhenbenwo.com/prod-api'; /* 根域名 */
        return config
    })
    
    // 请求拦截
    uni.$uv.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
        // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
     //    config.data = config.data || {}
        // // 根据custom参数中配置的是否需要token,添加对应的请求头
        // if(config?.custom?.auth) {
        //  // 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
        //  config.header.token = vm.$store.state.userInfo.token
        // }
        const token = uni.getStorageSync('token');
        //console.log('token----',token)
        if (token) {
            config.header.Authorization = token; // 设置 Authorization 头部
        }
        return config 
    }, config => { // 可使用async await 做异步操作
        return Promise.reject(config)
    })
    
    // 响应拦截
    uni.$uv.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
        //return response.data
        const res = response.data
        const token = uni.getStorageSync('token');
        //console.log('拦截器---',res)
        if(res.code == 401){ //判断token 过期 跳转重新登录
            //ElMessage.error("请先登录!")
            // uni.showToast({
            //  title: res.msg,
            //  duration: 2000,
            //  icon: 'none'
            // });
            uni.removeStorageSync('token');
            uni.showToast({
                title: '请重新登录!',
                duration: 2000,
                icon: 'none'
            });
            uni.reLaunch({
                url: '/pages/login/login'
            });
            // setTimeout(() => {
            //  //window.location.href = '/';
                
            // }, 1000);
            return
        }
        // if(response.code == 502){
        //  uni.showToast({
        //      title: '服务器错误,请稍后重试',
        //      duration: 2000,
        //      icon: 'none'
        //  });
        //  return
        // }
        return res;
    }, (response) => { 
        // 对响应错误做点什么 (statusCode !== 200)
        return Promise.reject(response)
    })
}