zoukankan      html  css  js  c++  java
  • fetch方法封装

    /* http.js */
    import 'whatwg-fetch'
    
    // HTTP 工具类
    export default class Http {
        static async request(method, url, data) {
            const param = {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                }
            };
    
            if (method === 'GET') {
                url += this.formatQuery(data)
            } else {
                param['body'] = JSON.stringify(data)
            }
    
            // Tips.loading(); // 可调用 loading 组件
    
            return fetch(url, param).then(response => this.isSuccess(response))
                    .then(response => {
                        return response.json()
                })
        }
    
        // 判断请求是否成功
        static isSuccess(res) {
            if (res.status >= 200 && res.status < 300) {
                return res
            } else {
                this.requestException(res)
            }
        }
    
        // 处理异常
        static requestException(res) {
            const error = new Error(res.statusText)
    
            error.response = res
    
            throw error
        }
        
        // url处理
        static formatQuery(query) {
            let params = [];
    
            if (query) {
                for (let item in query) {
                    let vals = query[item];
                    if (vals !== undefined) {
                        params.push(item + '=' + query[item])
                    }
                }
            }
            return params.length ? '?' + params.join('&') : '';
        }
        
        // 处理 get 请求
        static get(url, data) {
            return this.request('GET', url, data)
        }
        
        // 处理 put 请求
        static put(url, data) {
            return this.request('PUT', url, data)
        }
        
        // 处理 post 请求
        static post(url, data) {
            return this.request('POST', url, data)
        }
        
        // 处理 patch 请求
        static patch(url, data) {
            return this.request('PATCH', url, data)
        }
        
        // 处理 delete 请求
        static delete(url, data) {
            return this.request('DELETE', url, data)
        }
    }
    

      

  • 相关阅读:
    再谈H2的MVStore与MVMap
    log4j动态日志级别调整
    wireshark抓文件上传的包的结果记录
    struts2对properties资源的处理
    Spring core resourc层结构体系及JDK与Spring对classpath中资源的获取方式及结果对比
    [工具使用] visualvm 通过jmx不能连接
    oracle 安装 启动listener 建库相关
    vscode
    XSSFWorkbook
    TearmQuery()
  • 原文地址:https://www.cnblogs.com/feng3037/p/11412650.html
Copyright © 2011-2022 走看看