当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 原生Javascript使用fetch发起请求_模拟get|post|文件流下载等

原生Javascript使用fetch发起请求_模拟get|post|文件流下载等

2020年04月03日  | 移动技术网IT编程  | 我要评论
有时候,我们无法借助熟悉的jquery发起请求,原生JS里是支持fetch函数的,这是个高度封装的方法,帮助我们做了很多底层的封装,下面列举一些发起请求的示例: 1-发起Get请求: //httpGet请求 var httpGet = async function (getUrl) { var op ...

  有时候,我们无法借助熟悉的jquery发起请求,原生js里是支持fetch函数的,这是个高度封装的方法,帮助我们做了很多底层的封装,下面列举一些发起请求的示例:

 

  1-发起get请求:

//httpget请求
    var httpget = async function (geturl) {
        var opts = {
            method: "get",
            credentials: 'include' // 强制加入凭据头
        }
        await fetch(geturl, opts).then((response) => {
            return response.text();
        }).then((responsetext) => {
            result = responsetext;
        }).then((error) => {

        });
        return result;
    };

 

  2-发起get文件流-支持设置保存文件名-下载:

    //执行httpget下载
    var httpdownloadfile = 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);
        }).then((error) => {

        });
    };

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网