zoukankan      html  css  js  c++  java
  • 用ES6和fetch封装网络请求

     导读:

    fetch: 
    这个方法是ES2017中新增的特性,这个特性出来后给人一种传统ajax已死的感觉,其实它的作用是替代浏览器原生的XMLHttpRequest异步请求,
    我们在日常的开发中,基本不会自己去写XMLHttpRequest,主要是太复杂了,都是使用已经封装好了的各种插件,常用的有jquery。npm包管理工具也提供了axios,request等模块。
    而有了fetch后我们就可以在不用这些插件的情况下快速简单的实现异步请求了。

    async/await 能使得我们在编写异步代码时像同步一样的方式来编写。具体是将异步执行的代码封装了或者作为模块导入即可。

    fetch.js为封装好的模块,调用方式如下:

    另起一个getData.js用来封装所有的Service,调用fetch

    例 :

    getData.js

    import fetch from '../config/fetch'
    
    /**
     * 获取首页默认地址
     */
    
    export const cityGuess = () => fetch('/v1/cities', {
        type: 'guess'
    });
    /**
     * 获取搜索地址
     */
    
    export const searchplace = (cityid, value) => fetch('/v1/pois', {
        type: 'search',
        city_id: cityid,
        keyword: value
    });
    
    
    /**
     * 获取msite页面地址信息
     */
    
    export const msiteAddress = geohash => fetch('/v2/pois/' + geohash);

    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);
                const responseJson = await response.json();
                return responseJson
            } catch (error) {
                throw new Error(error)
            }
        } else {
        // 如果浏览器不支持 fetch
            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)
                        }
                    }
                }
            })
        }
    }
  • 相关阅读:
    简单批处理内部命令简介(转)
    CPU 内存 频率 DDR DDR2 DDR3
    python 正则表达式
    bat 脚本 > >> 管道
    python 多进程 无数进程 重复进程 死机
    NLP相关期刊和会议
    deamon tools dtsoft virtual cdrom device 失败 错误
    占位
    2011年07月03日的日记
    每周总结(第二周)
  • 原文地址:https://www.cnblogs.com/amunamuna/p/8984139.html
Copyright © 2011-2022 走看看