• 原生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();
  • 相关阅读:
    PHP学习笔记
    $POST 、$HTTP_RAW_POST_DATA、php://input三者之间的区别
    APACHE支持.htaccess以及 No input file specified解决方案
    PHP常用函数总结
    PHP网页的工作原理
    Lamp源码安装参考教程
    php相关配置
    PHP技巧:提高PHP性能的53个技巧
    面向对象工具
    面向对象基础
  • 原文地址:https://www.cnblogs.com/lxhbky/p/12852864.html
Copyright © 2020-2023  润新知