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

在写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';
                }
            }
        )
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章