封装 axios

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

1. 引入 axios 、 Element 、qs

    
    
    

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


你可能感兴趣的:(封装 axios)