http.js 3.34 KB
/**
 * axios 全局配置
 */

import axios from 'axios'
import router from '../router'
import { Message, Loading } from 'element-ui';
import md5 from 'blueimp-md5'

function cleanArray(actual) {
    const newArray = []
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i])
        }
    }
    return newArray
}

function param2(json) {
    if (!json) return ''
    return cleanArray(
        Object.keys(json).map(key => {
            if (json[key] === undefined ||
                json[key] === null
            ) return ''
            return encodeURIComponent(key) + '=' + json[key]
        })
    ).join('&')
}

const Axios = axios.create({
    timeout: 0, //设置请求超时时间
    withCredentials: true, // 是否允许带cookie这些
    headers: {
        "Content-Type": "application/json;charset=UTF-8"
    }
})

window.axios = Axios;

let loading //定义loading变量

function startLoading() { //使用Element loading-start 方法
    loading = Loading.Axios({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoading() { //使用Element loading-close 方法
    loading.close()
}

//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

/**@param
 * 请求前的拦截器
 */
Axios.interceptors.request.use((config) => {
    const suffix = '4c413628731691abc99eb2fca5f69aab'
    const { method, params, data } = config
    const token = localStorage.getItem('atoken');
    // config.headers['app-code'] = 1
    //截取API添加时间戳防止请求缓存
    if (config.url.indexOf('codes/countries') < 1) {
        if (config.url.indexOf('cates') < 1) {
            if (token) {
                config.headers.authorization = token;
                //showFullScreenLoading();
            } else {
                router.push('/');
            }
        }
    }
    const signalStr = method.toUpperCase() +
        (params ? param2(params) : '') +
        (data ? JSON.stringify(data) : '') +
        suffix + (config.headers.Authorization ? config.headers.Authorization : '');

    const hashSignature = md5(signalStr)
    config.headers['signature'] = hashSignature
    return config
}, function(err) {
    //tryHideFullScreenLoading();
});


/**
 * @param
 * 响应前的拦截器
 */
Axios.interceptors.response.use((res) => {
    //tryHideFullScreenLoading();
    if (res.data) {
        if (res.data.ecode === 401) {
            Message({
                type: 'error',
                message: res.data.enote
            })
            router.replace('/');
        }
    }
    return res;
}, function(err) {
    //tryHideFullScreenLoading();
    return Promise.reject(err);
})

export default Axios