自定义封装fetch

本文介绍如何根据WhatWG Fetch规范自定义封装fetch API,实现更便捷的网络请求。通过示例展示调用方式,探讨封装过程中的关键点和优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// import 'es5-shim' //由于 IE8 是 ES3,需要引入 ES5 的 polyfill
// require('es6-promise').polyfill(); //支持IE浏览器,引入 Promise 的 polyfill
// import 'whatwg-fetch' //解决移动浏览器兼容性问题
// import 'fetch-detector' //引入 fetch 探测库
// import 'fetch-ie8' //引入 fetch 的 polyfill
let baseUrl = ''
export default async(url = '', data = {}, type = 'GET', contentType = 'application/json', method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;
    contentType = contentType.toLowerCase();
    if (type === 'GET') {
        let dataStr = '';
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&'
        })
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr;
    }
    if (window.fetch && method === 'fetch') {
        let requestConfig = {
            credentials: 'include',
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': contentType
            },
            mode: 'cors',
            cache: 'force-cache'
        }
        if (type === 'POST') {
            if (contentType === 'application/x-www-form-urlencoded') {
                // let formData = new FormData();
                // Object.keys(data).forEach(key => {
                //     formData.append(key, data[key])
                // })
                let dataStr = '';
                Object.keys(data).forEach(key => {
                    dataStr += key + '=' + data[key] + '&'
                })
                dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
                requestConfig.body = dataStr;
            } else if (contentType === 'application/json') {
                requestConfig.body = JSON.stringify(data);
            } else {
                console.log('unkonwn');

            }
        }

        try {
            const res = await fetch(url, requestConfig);
            const dataObj = await res.json();
            return dataObj;
        } catch (error) {
            throw new Error(error)
        }

    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest()
            } else {
                requestObj = new ActiveXObject('Microsoft.XMLHTTP')
            }
            let dataStr = '';
            if (type === 'POST') {
                if (contentType === 'application/x-www-form-urlencoded') {
                    Object.keys(data).forEach(key => {
                        dataStr += key + '=' + data[key] + '&'
                    })
                    dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
                } else if (contentType === 'application/json') {
                    dataStr = JSON.stringify(data);
                } else {
                    console.log('unkonwn');

                }
            }
            requestObj.open(type, url, true);
            requestObj.setRequestHeader('Content-type', contentType);
            requestObj.send(dataStr);
            requestObj.onreadystatechange = function(e) {
                if (e.target.readyState === 4) {
                    if (e.target.status === 200) {
                        let obj = e.target.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(e.target.status)
                    }
                }
            }
        })
    }
}

示例:

export const login = (data) => {
    return fetch('/login', data, 'POST', 'application/x-www-form-urlencoded')
 };

调用:

login(data).then(res=>{
    console.log(res)
}).catch(error=>{
    console.log(error)
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值