zoukankan      html  css  js  c++  java
  • 原生JS-封装http请求类

      前言:如何使用纯原生JS封装关于,http请求的一个帮助类呢?  借助function抽象成类,借助fetch封装请求方法体。

      下面是JS封装类:

    function HttpClient(){
        var _this=this;
    
        var getkey=function(obj) {
            var arr = []
            var str = ''
            for (const key in obj) {
                arr.push(key + "=" + obj[key])
            }
            str = arr.join('&');
            return str;
        };
    
        _this.Get=async function(url,roolBackFunc){
            await fetch(url, {
              method: 'GET',
              credentials: 'include'
            }).then(function(response) {
              return response.text();
            }).then(function(responseText){
               roolBackFunc(responseText);
            });
        };
        
        //执行httpGet下载
        _this.GetFile = async function (getUrl, fileName) {
            var opts = {
                method: "GET",
                credentials: 'include' // 强制加入凭据头
            }
            await fetch(getUrl, opts).then((response) => {
                return response.blob();
            }).then((blob) => {
                var url = window.URL.createObjectURL(blob);
                var a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                a.click();
                window.URL.revokeObjectURL(url);
    
                console.info("下载完成:" + getUrl);
            }).then((error) => {
    
            });
        };
    
        _this.Post_form=async function(url,postData,roolBackFunc){
            await fetch(url, {
              method: 'POST',
              credentials: 'include',
              mode: "cors",
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              body:getkey(postData)
            }).then(function(response) {
              return response.text();
            }).then(function(responseText){
                roolBackFunc(responseText);
            });
        }
    }
    
    window["HttpClient"]=new HttpClient();
  • 相关阅读:
    Oracle数据导出到MySql
    ORA04031 shared_pool 不能分配足够内存或磁盘碎片
    IDEA那些好用的插件
    MySQL基础篇增删改查
    SpringBoot项目部署在阿里云
    三、Mybatis相应API
    chrome的书签备份
    redis踩坑
    四、Mybatis的Dao层实现
    MySQL基础篇函数
  • 原文地址:https://www.cnblogs.com/lxhbky/p/12852864.html
Copyright © 2011-2022 走看看