元生JS-パッケージhttp要求類

4317 ワード

はじめに、どのように純原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();