zhangfei
2025-06-03 14c90f4513a26dbc30960121c57a3cdf60996aa3
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
import {
    ACCESSTOKEN,
    config
} from '@/common/config.js'
import util from '@/common/util.js'
function getToken() {
    let token = uni.getStorageSync("sessionToken")
    return token
  }
const install = (Vue, vm) => {
    Vue.prototype.$u.http.setConfig({
        baseUrl: config.baseUrl,
        dataType: 'json',
        showLoading: false,
        loadingText: '加载中...',
        timeout: 5 * 60 * 1000, //超时时间 1分钟
        loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
        originalData: false, // 是否在拦截器中返回服务端的原始数据
        loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
        // 配置请求头信息
        header: {
            'Accept': 'application/json, text/plain, */*',
        }
    });
    Vue.prototype.$u.http.interceptor.request = (config) => {
        // 引用token
        const TOKEN = getToken()
        if (TOKEN) {
            config.header[ACCESSTOKEN] = 'Bearer' + " " + TOKEN;
        } else {
            delete config.header[ACCESSTOKEN]
        }
        // DEBUG && console.log('请求参数', config);
        return config;
    }
 
    // 响应拦截,如配置,每次请求结束都会执行本方法
    Vue.prototype.$u.http.interceptor.response = (res) => {
        // console.log("请求结果=", res);
        if (res.code == 200) {
            // res为服务端返回值,可能有code,result等字段
            // 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
            // 如果配置了originalData为true,请留意这里的返回值
            return res;
        } else if (res.code == 401) {
            // 假设401为token失效,这里跳转登录
            // vm.$u.toast(res.msg || "未知错误");
            vm.$u.vuex('userInfo', null)
            vm.$u.vuex('token', null)
            uni.removeStorageSync("sessionToken")
            setTimeout(() => {
                uni.reLaunch({
                    url: '/pages/index/index'
                })
            }, 500)
            return false;
        } else {
            vm.$u.toast(res.msg || "未知错误");
            // 如果返回false,则会调用Promise的reject回调,
            // 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
            return false;
        }
    }
}
 
export default {
    install
}