Fetch 網(wǎng)絡(luò)請(qǐng)求簡(jiǎn)單封裝鲁森,支持超時(shí)入口

拒絕多bb,直接上代碼,以下是Fetch網(wǎng)絡(luò)封裝類宫患,遵循ES6規(guī)范。

class FetchUtil {

    init(){
        this.url           = '';
        this.method        = 'GET';
        this.headers       = {};
        this.body_type     = 'form';
        this.bodys         = {};
        this.credentials   = 'omit';
        this.return_type   = 'json';
        this.overtime      = 0;
        this.firstThen     = undefined;

        return this;
    }


    setUrl(url){
        this.url = url;
        return this;
    }

    setMethod(val){
        this.method = val;
        return this;
    }

    setBodyType(val){
        this.body_type = val;
        return this;
    }

    setReturnType(val){
        this.return_type = val;
        return this;
    }

    setOvertime(val){
        this.overtime = val;
        return this;
    }

    setHeader(name, val=null){
        if(typeof name == 'string'){
            this.headers[name] = val;
        }else if(typeof name == 'object'){
            Object.keys(name).map((index)=>{
                this.headers[index] = name[index];
            });
        }

        return this;
    }

    setBody(name, val=null){
        if(typeof name == 'string'){
            this.bodys[name] = val;
        }else if(typeof name == 'object'){
            Object.keys(name).map((index)=>{
                this.bodys[index] = name[index];
            });
        }
        return this;
    }

    setCookieOrigin(){
        this.credentials = 'same-origin';
        return this;
    }

    setCookieCors(){
        this.credentials = 'include';
        return this;
    }

    thenStart(then) {
        this.firstThen = then;
        return this;
    }

    dofetch(){
        let options         = {};
        options.method      = this.method;
        options.credentials = this.credentials;

        options.headers = this.headers;

        if({} != this.bodys && this.method != 'GET'){
            if('form' == this.body_type){
                this.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
                let data = '';
                Object.keys(this.bodys).map((index) => {
                    let param = encodeURI(this.bodys[index]);
                    data += `${index}=${param}&`;
                });
                options.body = data;
            }else if('file' == this.body_type){
                let data = new FormData();
                Object.keys(this.bodys).map((index) => {
                    data.append(index, this.bodys[index]);
                });
                options.body = data;
            }else if('json' == this.body_type){
                options.body = JSON.stringify(this.bodys);
            }
        }

        return Promise.race([
                    fetch(this.url,options),
                    new Promise((resolve, reject) => {
                        setTimeout(() => reject(new Error('request timeout')), this.overtime ? this.overtime : 30 * 1000);
                    })
                ]).then(
                    (response) => {
                        if (this.firstThen) {
                            let tempResponse = this.firstThen(response);
                            if (tempResponse) {
                                return tempResponse;
                            }
                        }
                        return response;
                    }
                ).then(
                    (response) => {
                        if('json' == this.return_type){
                            return response.json();
                        }else if('text' == this.return_type){
                            return response.text();
                        }else if('blob' == this.return_type){
                            return response.blob();
                        }else if('formData' == this.return_type){
                            return response.formData();
                        }else if('arrayBuffer' == this.return_type){
                            return response.arrayBuffer();
                        }
                    }
                );
    }

}

module.exports = FetchUtil;

用法舉例:
POST請(qǐng)求

 //工具類實(shí)例可重用手幢,建議一個(gè)實(shí)例化一次之后復(fù)用

 let fetchUtil = new FetchUtil();



 fetchUtil.init()

 .setUrl('http://gank.io/api/random/data/Android/20')

 .setMethod('POST')

 .setOvertime(30 * 1000)

 .setHeader({

        'Accept': 'application/json',

        'Content-Type': 'application/json',

        'DEVICE-ID': 'iphone6',

        'SYSTEM': 'ios/android',

    })

 .setBody('name', 'test')

 .dofetch()

 .then((data) => {

        console.log('=> data: ', data);

    })

 .catch((error) => {

        console.log('=> catch: ', error);

    });



GET請(qǐng)求:

 //工具類實(shí)例可重用捷凄,建議一個(gè)實(shí)例化一次之后復(fù)用

 let fetchUtil = new FetchUtil();



 fetchUtil.init()

 .setUrl('http://gank.io/api/random/data/Android/requestData(params)?name=zhangsan&password=123456')

 .setMethod('POST')

 .setOvertime(30 * 1000)

 .setHeader({

        'Accept': 'application/json',

        'Content-Type': 'application/json',

        'DEVICE-ID': 'iphone6',

        'SYSTEM': 'ios/android',

    })

 .dofetch()

 .then((data) => {

        console.log('=> data: ', data);

    })

 .catch((error) => {

        console.log('=> catch: ', error);

    });



以下是方法說(shuō)明:

  • init() 初始化工具類

  • setUrl(url:string) 設(shè)置請(qǐng)求URL

  • setMethod(method:string) 設(shè)置請(qǐng)求方式,'GET'/'POST'/'PUT'/'DELETE'围来,默認(rèn)'GET'

  • setBodyType(type:string) 設(shè)置請(qǐng)求body類型跺涤,'form'/'file'/'json',默認(rèn)'form'

  • setReturnType(type:string) 設(shè)置返回data類型管钳,'json'/'text'/'blob'/'formData'/'arrayBuffer'钦铁,默認(rèn)'json'

  • setOvertime(time:number) 設(shè)置超時(shí)時(shí)間,毫秒

  • setHeader(name:string/object, value:string) 設(shè)置Header才漆,name若為字符串牛曹,則name和value為header鍵值對(duì)數(shù)據(jù),若name為object醇滥,則name為header鍵值對(duì)對(duì)象

  • setBody(name:string/object, value:string) 設(shè)置請(qǐng)求body黎比,參數(shù)同上

  • thenStart(then:function) 設(shè)置請(qǐng)求成功后第一個(gè)回調(diào)方法then,通常用于處理網(wǎng)絡(luò)返回的第一筆數(shù)據(jù)鸳玩,需要將此對(duì)象return出去阅虫,交由后面的then處理

  • dofetch() 執(zhí)行請(qǐng)求

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市不跟,隨后出現(xiàn)的幾起案子颓帝,更是在濱河造成了極大的恐慌,老刑警劉巖窝革,帶你破解...
    沈念sama閱讀 219,110評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件购城,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡虐译,警方通過(guò)查閱死者的電腦和手機(jī)瘪板,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)漆诽,“玉大人侮攀,你說(shuō)我怎么就攤上這事锣枝。” “怎么了兰英?”我有些...
    開封第一講書人閱讀 165,474評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵撇叁,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我箭昵,道長(zhǎng)税朴,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評(píng)論 1 295
  • 正文 為了忘掉前任家制,我火速辦了婚禮,結(jié)果婚禮上泡一,老公的妹妹穿的比我還像新娘颤殴。我一直安慰自己,他們只是感情好鼻忠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評(píng)論 6 392
  • 文/花漫 我一把揭開白布涵但。 她就那樣靜靜地躺著,像睡著了一般帖蔓。 火紅的嫁衣襯著肌膚如雪矮瘟。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評(píng)論 1 305
  • 那天塑娇,我揣著相機(jī)與錄音澈侠,去河邊找鬼。 笑死埋酬,一個(gè)胖子當(dāng)著我的面吹牛哨啃,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播写妥,決...
    沈念sama閱讀 40,418評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼拳球,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了珍特?” 一聲冷哼從身側(cè)響起祝峻,我...
    開封第一講書人閱讀 39,332評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎扎筒,沒(méi)想到半個(gè)月后莱找,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,796評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡砸琅,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評(píng)論 3 337
  • 正文 我和宋清朗相戀三年宋距,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片症脂。...
    茶點(diǎn)故事閱讀 40,110評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡谚赎,死狀恐怖淫僻,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情壶唤,我是刑警寧澤雳灵,帶...
    沈念sama閱讀 35,792評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站闸盔,受9級(jí)特大地震影響悯辙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜迎吵,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評(píng)論 3 331
  • 文/蒙蒙 一躲撰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧击费,春花似錦拢蛋、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至圆仔,卻和暖如春垃瞧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背坪郭。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工个从, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人截粗。 一個(gè)月前我還...
    沈念sama閱讀 48,348評(píng)論 3 373
  • 正文 我出身青樓信姓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親绸罗。 傳聞我的和親對(duì)象是個(gè)殘疾皇子意推,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)珊蟀,斷路器菊值,智...
    卡卡羅2017閱讀 134,662評(píng)論 18 139
  • # 一度蜜v3.0協(xié)議 --- # 交互協(xié)議 [TOC] ## 協(xié)議說(shuō)明 ### 請(qǐng)求參數(shù) 下表列出了v3.0版協(xié)...
    c5e350bc5b40閱讀 650評(píng)論 0 0
  • Address:https://www.zybuluo.com/XiangZhou/note/208532 Exp...
    天蠍蒗漫閱讀 11,314評(píng)論 2 55
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法育灸,內(nèi)部類的語(yǔ)法腻窒,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法磅崭,線程的語(yǔ)...
    子非魚_t_閱讀 31,639評(píng)論 18 399
  • 明天就是年三十了砸喻。 跌跌撞撞柔逼,跌跌撞撞蒋譬,白丁小館也已經(jīng)滿月了。這幾天一直都想寫點(diǎn)什么愉适,可老是被你們這群“...
    火鍋白丁造閱讀 868評(píng)論 0 0