原生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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM