封装 原生 fetch

1, 简介  

  fetch方法是 Fetch API的一个方法,提供了一种简单、合理的方式来跨网络异步获取资源。

  与原来的XMLHttpRequest比较,fetch更容易与其他的技术结合:比如service workers。还提供了单个逻辑位置来定义其他HTTP相关概念,例如CORS和HTTP的扩展。

  默认情况下fetch不会从服务端接收或发送cookies,如果需要发送则设置credentials选项(默认的credentials为same-origin)。

2,参数

  fetch(urlinit={})    

     url: 为请求的url路径,  也可以是Request对象(new Request( '请求路径'));

     init: 配置对象,可选的参数有

      • credentials:  能否发送带凭据的请求;  参数为omit、same-origin 或者include
      • headers:请求头, 可以使用对象字面量,也可以使用Headers()构造函数创建一个headers对象。
      • method: 请求方法, get post put delete option等。。
      • cros: 请求是否允许跨域,   参数为 cors、no-cors或same-origin;
      • cache:请求的cache模式, 参数为 default、no-store、reload、no-cache、force-cache或only-if-cached。
      • body:请求主体。 get和head方法不包含body。body可以是以下类型的实例(ArrayBuffer、ArrayBufferView、Blob/File、string、URLSearchParams、FormData), body类包含了以下的方法,可以返回解析后的promise对象和数据(arrayBuffer()、blob() , json() , text() , formData());
      • 等等.....

3,fetch的封装

async function fetch(url, data = {}, method = 'get', way = 'fetch') {
    method = method.toUpperCase();
    if (method === 'GET') {
        let str = '';
        Object.keys(data).forEach(item => {
            str += `${item}=${data[item]}&`;
        });
        if (str) {
            url = url + '?' + str.slice(0, -1);
        }
    }

    if (window.fetch && way === 'fetch') {
        let reqInit = {
            credentials: 'inclued',
            method,
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            cache: 'force-cache'
        };
        if (method === 'POST') {
            Object.assign(reqInit, {
                body: JSON.stringify(data)
            })
        }
        try {
            const res = await fetch(url, reqInit);
            const resJson = res.json();
            return resJson;
        } catch(e) {
            Promise.reject(e);
        }
    } else {
        return new Promise((resolve, reject) => {
            let httpReqObj;
            if (window.XMLHttpRequest) {
                httpReqObj = new XMLHttpRequest();
            } else {
                httpReqObj = new ActiveXObject('Microsoft.XMLHTTP');
            }

            httpReqObj.open(method, url, true);
            httpReqObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            httpReqObj.send(method === 'POST' ? JSON.stringify(data) : null);
            httpReqObj.onreadystatechange = () => {
                if (httpReqObj.readyState === 4){
                    if (httpReqObj.status === 200) {
                        let obj = httpReqObj.response;
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj);
                    } else {
                        reject(httpReqObj);
                    }
                }
            }
        })
    }
}

  如果不支持fetch或者你不想用fetch, 就改为用xmlhttprequest来发送, 里面的很多参数我都是根据自己项目的需求写死了, 想写的更灵活的小伙伴们可以自行的再封装。

  

 

  

posted @ 2019-04-17 15:41  ken丶123  阅读(419)  评论(0编辑  收藏  举报