Fetch 网络请求简单封装,支持超时入口

拒绝多bb,直接上代码,以下是Fetch网络封装类,遵循ES6规范。

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请求

 //工具类实例可重用,建议一个实例化一次之后复用

 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请求:

 //工具类实例可重用,建议一个实例化一次之后复用

 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);

    });



以下是方法说明:

  • init() 初始化工具类

  • setUrl(url:string) 设置请求URL

  • setMethod(method:string) 设置请求方式,'GET'/'POST'/'PUT'/'DELETE',默认'GET'

  • setBodyType(type:string) 设置请求body类型,'form'/'file'/'json',默认'form'

  • setReturnType(type:string) 设置返回data类型,'json'/'text'/'blob'/'formData'/'arrayBuffer',默认'json'

  • setOvertime(time:number) 设置超时时间,毫秒

  • setHeader(name:string/object, value:string) 设置Header,name若为字符串,则name和value为header键值对数据,若name为object,则name为header键值对对象

  • setBody(name:string/object, value:string) 设置请求body,参数同上

  • thenStart(then:function) 设置请求成功后第一个回调方法then,通常用于处理网络返回的第一笔数据,需要将此对象return出去,交由后面的then处理

  • dofetch() 执行请求

你可能感兴趣的:(Fetch 网络请求简单封装,支持超时入口)