window.fetch 使用加兼容处理

2021-07-29  本文已影响0人  浅浅_2d5a

官网
https://www.w3cschool.cn/fetch_api/fetch_api-6ls42k12.html

干什么用的?

是浏览器上获取异步资源请求的全局fetch方法,是基于基于Promise的。
可以替代XMLHttpRequest 进行异步请求

兼容性

查看兼容行网址
https://www.caniuse.com/

image.png
例子

fetch.js

import { baseUrl } from './env'

export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            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': 'application/json' //请求信息的格式
            },
            mode: "cors",
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
        
        try {
            const response = await fetch(url, requestConfig); //Promise对象 所以用await
            console.log('response1',response )  // Response对象
            const responseJson =  await response.json(); //fetch中的json方法将Response对象转成json对象
            console.log('responseJson',responseJson)
            return responseJson
        } catch (error) {
            throw new Error(error)
        }
    } else { //不支持window.fetch的还用XMLHttpRequest 结合Promise
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}

api接口定义部分内容
export const login = data => fetch('/admin/login', data, 'POST');

上一篇下一篇

猜你喜欢

热点阅读