Blame view

src/utils/request.js 2.65 KB
1 2 3
/**
 * 此文件主要创建 axios 实例,然后添加请求拦截器和响应拦截器
 */
赵千 committed
4
import axios from 'axios'
5 6 7
import { Message } from 'element-ui'
import { startLoadingAddCount, endLoadingSubCount } from './requestLoading'

赵千 committed
8 9
// create an axios instance
const service = axios.create({
10 11
    baseURL: process.env.VUE_APP_BASE_API,
    withCredentials: true,  //是否允许跨域
赵千 committed
12
    headers: {
liangyifan committed
13 14
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization':'bearer AT-16-oqkOHiUSsDdFA-eAZ49k2rJQDTzQpClO'
赵千 committed
15
    },
16
    timeout: 15000
赵千 committed
17 18 19 20 21
})

// request interceptor
service.interceptors.request.use(
    config => {
22 23 24
        if (config.showLoading) {
            startLoadingAddCount(config.loadingTarget);
        }
赵千 committed
25 26 27
        return config
    },
    error => {
任超 committed
28
        if (error.showLoading) {
29 30 31
            endLoadingSubCount(config.loadingTarget);
        }
        Message.error('请求超时!');
赵千 committed
32 33 34 35 36 37 38
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
39 40
        if (response.config.showLoading) {
            endLoadingSubCount();
赵千 committed
41
        }
42 43 44 45 46 47 48
        /**
         * 对响应数据判断:
         *  如果成功返回数据,就通过return把数据返出去
         *  如果请求不成功,就在拦截器这里统一处理(组件的代码就不用关注错误的情况了)
         */
        if (response.status == 200) {
            return response.data;
赵千 committed
49
        } else {
50
            handleErrorData(response.data);
赵千 committed
51
        }
52
        return response;
赵千 committed
53 54
    },
    error => {
55 56 57 58 59 60
        // 对响应错误做点什么
        Message({
            message: '服务器异常,请联系管理员',
            type: 'error',
            duration: 5 * 1000
        })
任超 committed
61
        if (error.config.showLoading) {
任超 committed
62 63
            endLoadingSubCount();
        }
64
        return Promise.reject(error);
赵千 committed
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
//对错误信息的处理函数
function handleErrorData (errMes) {
    if (errMes.message) {
        Message.error(errMes.message);
    } else {
        switch (errMes.code) {
            case 401:
                Message.error("未授权,请重新登录!");
                break;
            case 403:
                Message.error("拒绝访问");
                break;
            case 404:
                Message.error("很抱歉,资源未找到!");
                break;
            case 500:
                Message.error("服务器错误!");
                break;
            case 504:
                Message.error("网络超时!");
                break;
            default:
                Message.error("服务正在联调中,请稍后!");
                break;
        }
    }
}

赵千 committed
95
export default service
96