前言:如何使用纯原生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();