axios的简单使用

import axios, { AxiosPromise, AxiosError, AxiosResponse } from 'axios';
// 对请求头的处理,与后端约定
axios.interceptors.request.use((config) => {
    let clientIP = window.vm.$store && window.vm.$store.getters.clientIP;
    if (clientIP) {
        config.headers['X-Client-Ip'] = clientIP;
    }
    return config;
});
// 处理返回结果
axios.interceptors.response.use((res) => {
    return res;
}, (err: AxiosError) => {
    window.vm.ajaxError(err.response);
    return Promise.reject(err);
});
// 定义通用的请求方法
async mixGet(url: string, params?: any, loading: boolean = true, headers: any = {}) {
        this.showLoading(loading);
        let res = await axios.get(url, { params, headers });
        loading && this.mixHideLoading();
        return res;
}
// 错误处理
ajaxError(err: AxiosResponse) {
        switch (err.status) {
            case 401:
                sessionStorage.clear();
                localStorage.clear();
                if (this.$route.path != '/') {
                    this.$router.replace('/');
                }
                location.reload();
                break;
            default:
                let message = err.data.message;
                if (message) {
                    this.mixShowTips(message, 'error');
                }
                break;
        }
}

你可能感兴趣的:(axios的简单使用)