【HAVENT原創】讓 axios 支持 jsonp

由於不想讓再引用新的第三方組件了,因此執念了一下,因而搜索到了下面的代碼javascript

//axios本版本不支持jsonp 本身拓展一個
axios.jsonp = (url) => {
    if(!url){
        console.error('Axios.JSONP 至少須要一個url參數!')
        return;
    }
    return new Promise((resolve,reject) => {
        window.jsonCallBack =(result) => {
            resolve(result)
        }
        var JSONP=document.createElement("script");
        JSONP.type="text/javascript";
        JSONP.src=`${url}&callback=jsonCallBack`;
        document.getElementsByTagName("head")[0].appendChild(JSONP);
        setTimeout(() => {
            document.getElementsByTagName("head")[0].removeChild(JSONP)
        },500)
    })
}

 

調試了一下,發現確實能用,可是存在一個缺陷,就是若是存在連續屢次的請求,都會回調到同一個函數上,這樣會致使獲取異步結果的時候只返回了最後一次的結果,因而乎調整了一下函數,保證每次都是命中本身對應的方法,寫的比較簡單,由於個人 index 不會重複,因此我沒作其餘校驗了,若是須要保證請求的惟一性,請將 index 參數設置爲惟一值(好比 時間戳 + 3位的隨機數)java

import axios from 'axios'
import es6Promise from 'es6-promise'


// HH: 擴展 axios,讓 axios 支持 jsonp
axios.jsonp = (url, index) => {
    if (!url) {
        console.error('Axios.JSONP 至少須要一個url參數!')
        return;
    }

    let callbackName = 'jsonCallBack' + index;
    return new Promise((resolve, reject) => {
        let JSONP = document.createElement("script");
        JSONP.type = "text/javascript";
        JSONP.src = `${url}&jsonpCall=${callbackName}`;
        document.getElementsByTagName("head")[0].appendChild(JSONP);

        window[callbackName] = (res) => {
            resolve(res)
        }

        setTimeout(() => {
            document.getElementsByTagName("head")[0].removeChild(JSONP)
        }, 500)
    })
}


export const jsonp = (url, index) => axios.jsonp(url, index)
相關文章
相關標籤/搜索