zoukankan      html  css  js  c++  java
  • 原生Javascript使用fetch发起请求_模拟get|post|文件流下载等

      有时候,我们无法借助熟悉的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) => {
    
            });
        };
  • 相关阅读:
    ios lazying load
    ios 单例模式
    ios 消息推送原理
    C#图片闪烁
    C#使窗体不显示在任务栏
    实时监测鼠标是否按下和鼠标坐标
    winfrom窗体的透明度
    C#获取屏幕的宽度和高度
    HDU 5171 GTY's birthday gift 矩阵快速幂
    HDU 5170 GTY's math problem 水题
  • 原文地址:https://www.cnblogs.com/lxhbky/p/12620086.html
Copyright © 2011-2022 走看看