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