封装 axios

2018-08-20  本文已影响859人  董懂同学

公司目前的技术栈,主要是Vue、Element UI、axios,因此封装 axios 也是使用 Element 的Message 组件

1. 引入 axios 、 Element 、qs

    <script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/qs/6.5.2/qs.min.js"></script>
    <script src="https://cdn.bootcss.com/element-ui/2.0.11/index.js"></script>

2.封装 axios

let config = {
    baseURL: location.origin,
    method: 'GET',
    headers: {
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    params: {},
    timeout: 10000,
    withCredentials: false,
    responseType: 'json',
    maxContentLength: 2000,
    validateStatus: function (status) {
        return status >= 200 && status < 300;
    },
    maxRedirects: 5,
    transformRequest: [data => Qs.stringify(data)],
    paramsSerializer: params => Qs.stringify(params),
    data: {
        XDEBUG_SESSION_START: 1
    }
};
let uAxios = axios.create(config);


// http request 拦截器
uAxios.interceptors.request.use(config => {
    config.headers.Authorization = 'Bearer ';
    return config;
}, error => {
    window.ELEMENT.Message.error({
        message: '请求超时!'
    });
    return Promise.reject(error);
});

// http response 拦截器
uAxios.interceptors.response.use(response => {
    if (response.status && response.status == 200 && response.data.code == 0) {
        window.ELEMENT.Message.error({message: response.data.msg});
        return;
    }
    return response;
}, error => {
    return Promise.resolve(error.response);
});

3. 使用 uAxios

<script src="/path/uAxios.js"></script>
上一篇下一篇

猜你喜欢

热点阅读