分享一下自己react项目中封装的axios

6 篇文章 0 订阅

在写react项目的时候,自己又重新封装了一次axios,回顾一下,尽管觉得还是有点冗余,持续优化中…

static ajax(options){
        let loading;
        //初始化参数
        let obj={
            url:'',
            method:'post',
            data:{},
            params:{},
            baseURL:serverUrl,
            timeout:10000,
            headers:{
                'Content-Type':  "application/json;charset=UTF-8"
            },
            withCredentials:true,//设置允许cookie
        }
        //传入参数替代初始参数
        for(let item in options){
            if(obj[item]!==undefined) { obj[item]=options[item]};
        }
        obj.params=obj.data;
        obj.data=''

        if (obj.data &&Object.is(obj.isShowLoading,true)){ //如果需要显示全局加载
            loading = document.getElementById('ajaxLoading');
            loading.style.display = 'block';
        }
        return new Promise( 
            async (resolve,reject)=>{
                await axios({
                ...obj
                }).then((response)=>{
                    if(!Object.is(response.status,200)) { reject(response.data); return; }
                    let res = response.data;
                    if (Object.is(res.code,0)) { resolve(res); return; }
                    if (Object.is(res.code,2)) {
                        sessionStorage.removeItem('jx_username');
                        sessionStorage.removeItem('jx_password');
                        history.push('/login');
                        res.message='登录失效,请重新登录';
                        reject(res);
                        return;
                    }
                    reject(res);
                    return;
                }).catch((res)=>{  
                        reject(res);
                })
                //取消加载
                if (obj.data && Object.is(obj.isShowLoading,true)) {
                    loading = document.getElementById('ajaxLoading');
                    loading.style.display = 'none';
                }
            }
        )
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值