requestUtil.js 4.31 KB
Newer Older
1 2 3 4
import axios from 'axios';
import { notification } from 'ant-design-vue';
import md5 from 'crypto-js/md5';
import { langUtil } from '.';
wb-ct393452's avatar
wb-ct393452 committed
5 6

// 跨域认证信息 header 名
7
const xsrfHeaderName = 'Authorization';
wb-ct393452's avatar
wb-ct393452 committed
8

9 10 11 12 13
axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true;
axios.defaults.xsrfHeaderName = xsrfHeaderName;
axios.defaults.xsrfCookieName = xsrfHeaderName;

陈浩玮's avatar
设备  
陈浩玮 committed
14 15
axios.defaults.baseURL = '/api';

16 17 18
/**
 * @param {*} info 提示函数
 */
水落(YangLei)'s avatar
水落(YangLei) committed
19
function loadResponseInterceptor({ router }) {
20
    axios.interceptors.request.use(
21
        function (config) {
22 23 24 25
            // 在发送请求之前做些什么
            config.headers = {
                ...config.headers,
                Authorization: getToken(),
26
                'X-Access-Lang': langUtil.get(),
27 28 29
            };
            return config;
        },
30
        function (error) {
31 32 33 34 35 36 37
            // 对请求错误做些什么
            return Promise.reject(error);
        },
    );

    // 添加响应拦截器
    axios.interceptors.response.use(
38
        function (response) {
39 40 41
            const { data } = response;
            // 2xx 范围内的状态码都会触发该函数。
            // 对响应数据做点什么
陈浩玮's avatar
tijiao  
陈浩玮 committed
42 43 44
            if (response.headers['content-disposition']) {
                return data;
            }
45 46 47
            if (data.code === 'sys.success') {
                return data.data;
            }
水落(YangLei)'s avatar
水落(YangLei) committed
48 49

            if (data.code === 'error.system.authc') {
50
                router.push({ path: '/login', query: { back: true } });
水落(YangLei)'s avatar
水落(YangLei) committed
51
            }
52 53
            notification.error({
                message: data.code,
54
                description: (h) => h('pre', data.message),
55
            });
水落(YangLei)'s avatar
水落(YangLei) committed
56

57 58
            return Promise.reject(data.message);
        },
59
        function (error) {
60 61 62 63
            // 超出 2xx 范围的状态码都会触发该函数。
            // 对响应错误做点什么
            notification.error({
                message: `${error.response.status} ${error.response.statusText}`,
64
                description: (h) => h('pre', error.message),
65 66 67 68 69
            });
            return Promise.reject(error);
        },
    );
}
wb-ct393452's avatar
wb-ct393452 committed
70 71 72

// http method
const METHOD = {
73 74 75 76 77
    GET: 'get',
    POST: 'post',
    PUT: 'put',
    DELETE: 'delete',
};
wb-ct393452's avatar
wb-ct393452 committed
78 79 80 81 82 83 84 85 86 87

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @param config token等信息
 * @returns {Promise<AxiosResponse<T>>}
 */
async function request(url, method, params, config) {
88 89 90 91 92 93 94 95 96 97 98 99
    switch (method) {
        case METHOD.GET:
            return axios.get(url, { params, ...config });
        case METHOD.POST:
            return axios.post(url, params, config);
        case METHOD.PUT:
            return axios.put(url, params, config);
        case METHOD.DELETE:
            return axios.delete(url, { params, ...config });
        default:
            return axios.get(url, { params, ...config });
    }
wb-ct393452's avatar
wb-ct393452 committed
100 101 102
}

/**
103 104 105
 * 解析 url 中的参数
 * @param url
 * @returns {Object}
wb-ct393452's avatar
wb-ct393452 committed
106
 */
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
function parseUrlParams(url) {
    const params = {};
    if (!url || url === '' || typeof url !== 'string') {
        return params;
    }
    const paramsStr = url.split('?')[1];
    if (!paramsStr) {
        return params;
    }
    const paramsArr = paramsStr.replace(/&|=/g, ' ').split(' ');
    for (let i = 0; i < paramsArr.length / 2; i++) {
        const value = paramsArr[i * 2 + 1];
        params[paramsArr[i * 2]] = value === 'true' ? true : value === 'false' ? false : value;
    }
    return params;
wb-ct393452's avatar
wb-ct393452 committed
122 123
}

124 125 126
const TOKEN_KEY = md5('TOKEN').toString();
function getToken() {
    return window.sessionStorage.getItem(TOKEN_KEY) ?? '';
wb-ct393452's avatar
wb-ct393452 committed
127 128
}

129 130
function setToken(val) {
    window.sessionStorage.setItem(TOKEN_KEY, val);
wb-ct393452's avatar
wb-ct393452 committed
131 132
}

133 134
function clearToken() {
    window.sessionStorage.removeItem(TOKEN_KEY);
wb-ct393452's avatar
wb-ct393452 committed
135 136
}

137 138
function checkAuthorization() {
    return !!getToken();
wb-ct393452's avatar
wb-ct393452 committed
139 140
}

陈浩玮's avatar
陈浩玮 committed
141 142
function delReq(url, params, config) {
    return request(url, METHOD.DELETE, params, config);
143 144 145 146 147 148 149 150 151 152
}

function getReq(url, params, config) {
    return request(url, METHOD.GET, params, config);
}

function postReq(url, data, config) {
    return request(url, METHOD.POST, data, config);
}

陈浩玮's avatar
陈浩玮 committed
153 154 155 156
function putReq(url, data, config) {
    return request(url, METHOD.PUT, data, config);
}

157 158 159 160 161 162 163 164 165 166 167
export {
    METHOD,
    request,
    parseUrlParams,
    loadResponseInterceptor,
    setToken,
    checkAuthorization,
    clearToken,
    delReq,
    getReq,
    postReq,
陈浩玮's avatar
陈浩玮 committed
168
    putReq,
169
};