axios 简单化

为什么选择axios?

1.使用axios可以统一做请求-响应拦截,例如响应时我们将响应信息拦截起来,判断状态码,从而弹出报错信息
2.设定请求超时,例如3000ms未响应则停止请求
3.基于promise,可以很方便地使用then或者catch来处理请求
4.自动转换json数据
4.等等

代码如下

import axios, { AxiosRequestConfig } from 'axios';
import qs from 'qs';
import { getToken, removeToken } from '@/utils/common';
import { Message, Loading } from 'element-ui';
import router from '@/router/index';
console.log(process.env.VUE_APP_BASE_API)
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, //完整的URL =   baseURL + url  
    timeout: 20000,
    withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
})
let loadinginstace: any;
// 请求拦截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
    const token = getToken();
    loadinginstace = Loading.service({
        fullscreen: true, lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    token && (config.headers.Authorization = token);
    return config;
}, (error: any) => {
    console.log(error)
    loadinginstace.close();

    return Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use(
    response => {
        //console.log(response)
        loadinginstace.close();
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    }, error => {
        loadinginstace.close();
        if (error.message.includes('timeout')) {
            console.log("错误")
            Message.error({
                showClose: true,
                message: '请检查网络再重新连接',
            });
            return Promise.reject('请检查网络再重新连接');
        } else if (error && error.response.status) {
            switch (error.response.status) {
                case 401:
                    router.replace({
                        path: '/login',
                        query: { redirect: router.currentRoute.fullPath }
                    });
                    break;
                case 403:
                    Message.error({
                        showClose: true,
                        message: '登录过期,请重新登录',
                    });
                    removeToken()

                    setTimeout(() => {
                        router.replace({
                            path: '/login',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        });
                    }, 1000);
                    break;
                case 404:
                    Message.error({
                        showClose: true,
                        message: '网络请求不存在',
                    });
                    setTimeout(() => {
                        router.replace({
                            path: '/404',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        });
                    }, 1000);
                    break;
                default:
                    Message.error({
                        showClose: true,
                        message: error.response.data.message,
                    });
                    return Promise.reject(error.response);
            }
        }



    }
)


// 请求方式的配置

export const post = (url: any, data?: any) => {  //  post
    return new Promise((resolve: any, reject: any) => {
        service({
            method: 'post',
            url,
            data: qs.stringify(data),
        }).then(
            res => {
                //console.log(res)
                return resolve(res.data);
            }
        ).catch(err => {
            reject(err.data)
        })
    })

}
export const get = (url: any, params?: any) => {  // get
    return new Promise((resolve: any, reject: any) => {
        service({
            method: 'get',
            url,
            params, // get 请求时带的参数
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    })

}


使用如下

import { post ,get} from "@/utils/http";
const aaa:(data: Porject.AddProjectType) => Promise = async (data: Porject.AddProjectType): Promise => {
    return post(
        "/project/add_project",
        data
    )
}


const bbb= (uuid:number) => {
    return get("/task/sectiontask",{puuid:uuid})    
}

多多指教 bye~~~

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