原生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) => {

        });
    };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM