Fetch封装方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046318/article/details/81123142

何为Fetch?

Fetch是一个与AJax请求功能相似的一个请求接口,并且只有浏览器该方法。Fetch的出现一方面是为了缓解原生XMLHTTPRequest实现起来比较杂乱的问题。下面是一个例子:

XHR对象实现Ajax请求:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';

    xhr.onload = function() {
        console.log(xhr.response);
    };

    xhr.onerror = function() {
        console.log("There is an error");
    };

    xhr.send();

Fetch实现Ajax请求:

fetch(url, {
    method: 'GET';
}).then(res => {
    res.json();
}).then(data => {
    console.log(data);
}).catch(error => {
    console.log(error.msg);
})

可以看到Fetch会比原生XHR简单很多,并且Fetch返回是一个Promise对象。然而,Fetch 请求默认是不带 cookie 的,需要设置请求参数,并且当服务器返回 400,500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,Fetch 才会被 reject

因此,在Fetch请求时,通常会做一层封装,我们可以用下面的方式去封装。

 function Fetch(url, options) {
     let init = {
         method: 'GET',
         headers: {
             'Content-Type': 'application/json'
         },
         credentials: 'include'                   //包含Cookie
     }
    // 合并请求
    Object.assign(init, options);

    //GET方法:查询字符附在url后面;

    if(init.method == 'GET' && options.data || init.method == 'HEAD') {
        let searchStr = '';
        if(options.data instanceof Object) {
            for(let i in options.data) {
                searchStr += ( i + '=' + options.data[i] );
            }
        }
        url = url + '?' + searchStr;
    }

    return fetch(url, init).then( res => {
        console.log(res);
        if(res.status === 200) {
            console.log(res);
            return res.json();
        } else {
            console.log('错误信息' + res.msg);
        }
        return res.json()
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log(error);
    })
}

猜你喜欢

转载自blog.csdn.net/u010046318/article/details/81123142