request.js 3.42 KB
import base from "@/config/baseUrl";
import store from '@/store';
import { judgeLogin } from '@/config/login';

// 初始化请求配置
uni.$u.http.setConfig((config) => {
    // var token = store.state.userInfo.token || (uni.getStorageSync('userInfo').token || undefined)
    /* config 为默认全局配置*/
    config.baseURL = base.baseUrl; /* 根域名 */
    config.header = {
        'Content-Type': 'application/x-www-form-urlencoded',
        // 'Authorization': 'Bearer ' + token
        
    }
    config.custom = {
        load:true,//是否显示加载动画
        isFactory: true,//true:返回的数据成功只返回data  false:返回response
        catch: true,//默认数据返回不成功进入catch返回
        // auth: true,//token
    }
    return config
})

// 请求拦截
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
    // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
    config.data = config.data || {}
    // 根据custom参数中配置的是否需要token,添加对应的请求头
    if(config?.custom?.auth) {
        config.header.token = store.state.userInfo.token
    }
    console.log("请求开始", config);
    if (config?.custom?.load) {
        //打开加载动画
        store.commit("setLoadingShow", true);
    }
    
    return config 
}, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
})

// 响应拦截
uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
    // 关闭加载动画
    store.commit("setLoadingShow", false);
    const data = response.data
    // 自定义参数
    const custom = response.config?.custom
    // code:  1、请求成功 -1、请求成功,没有更多参数 2、被迫下线重新登录、
    if(data.code == 1 || data.code == -1){
        if(data.code == -1){
            data.data = []
        }
        if(!custom.isFactory){
            return data
        }else{
            return data.data === undefined ? {} : data.data
        }
    }else if(data.code == 2){//被迫下线重新登录
        // 清空登录信息
        store.commit("emptyUserInfo");
        // 20秒节流,弹窗登录
        uni.$u.throttle(judgeLogin(), 20000)
        return new Promise(() => { })
    }else{
        // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
        if (custom.toast !== false) {
            uni.$u.toast(data.message || data.msg)
        }
        // 如果需要catch返回,则进行reject
        if (custom?.catch) {
            return Promise.reject(data)
        } else {
            // 否则返回一个pending中的promise,请求不会进入catch中
            return new Promise(() => { })
        }
    }
}, (response) => {
    // 关闭加载动画
    store.commit("setLoadingShow", false);
    // 对响应错误做点什么 (statusCode !== 200)
    let errorData = '请检查网络或服务器'
    let message = response.message || response.msg
    if(message == "request:fail url not in domain list") {
        errorData = '检查请求域名是否添加了域名白名单'
    }else if (message == 'request:fail timeout') {
        errorData = '请求超时:请检查网络'
    }else{
        errorData = message || '请检查网络或服务器'
    }
    uni.$u.toast(errorData)
    return Promise.reject(response)
})