axios 發get,post 請求小結

洲哥發表於2019-01-25

get 請求

    axios({
        url: `${Interface.xxx}`,
        method: `get`,
        params: {
            ....
        },
        headers: {
            `Content-Type`: `application/x-www-form-urlencoded`
        }
    ).then( res => res)
複製程式碼
    axios.get(url).then(res => res)
複製程式碼

post 請求

    axios({
        url: `${Interface.xxx}`,
        methods: `post`,
        data: data,
        transformRequest: [
            function(data) {
                return JSON.stringify(data)
            }
        ],
        headers: {
            `Content-Type`: `application/json; charset=utf-8`
        }
    }).then(res => res)
複製程式碼
   axios.post(url, toQueryString(query, {
        headers: {
            `Content-Type`: `application/x-www-form-urlencoded; chartset=utf-8`
        }
    }).then(res => res)
    
    // 過濾稀疏陣列
    // @params {Array}
    function cleanArray(arr) {
        const newArr = arr.filter( v => !v);
        return newArr;
    }
    
    //轉化為查詢字串
    function toQueryString(josn) {
        if(!json) return ``;
        retrun cleanArray(
            Object.keys(json).map(v => {
                if(json[v] === undefined) return ``;
                return encodeURIComponent(v) + "=" + encodeURIComponent(json[v]);
            })
        ).join("&")
    }
    
複製程式碼

相關文章