fetch簡單封裝

const fetchGet = function(url, params) {
    let list = [];
    for (let key in params) {
        let str = `${key}=${params[key]}`
        list.push(str);
    }
    const data = list.join('&');
    let gUrl = `${url}?${data}`;
    return fetch(gUrl).then(res => {
        return res.json();
    }).catch(err => {
        console.log(err);
    });
};
const fetchPost = function(url, params) {
    let formData = new FormData();
    for (let key in params) {
        formData.append(key, params[key])
    };
    return fetch(url, {
        body: formData,
        method: 'POST'
    }).then(res => {
        return res.json();
    }).catch(err => {
        console.log(err);
    })
};
const fetchAll = function(url, params, method='GET') {
    if (method === 'GET' || method === 'get') {
        return fetchGet(url, params);
    } 
    return fetchPost(url, params);
}
export default {
    fetchGet,
    fetchPost,
    fetchAll
}

使用:

import myFetch from './fetch.js';
// 通用,傳method,不傳默認(rèn)get
myFetch.fetchAll('http://xxxxxxxxxxxxx', {
     xxxxx: xxxxx, 
     xxxxx: 'xxxxxxxxxxxxxx'
 }).then(res => {
     console.log(res);
}).catch(err => {
     console.log(err);
})
// get
myFetch.fetchGet('http://xxxxxxxxxxxxx', {
     xxxxx: xxxxx, 
     xxxxx: 'xxxxxxxxxxxxxx'
 }).then(res => {
     console.log(res);
}).catch(err => {
     console.log(err);
})
// post
myFetch.fetchPost('http://xxxxxxxxxxxxx', {
     xxxxx: xxxxx, 
     xxxxx: 'xxxxxxxxxxxxxx'
 }).then(res => {
     console.log(res);
}).catch(err => {
     console.log(err);
})

參考文檔: MDN

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 導(dǎo)語 在項(xiàng)目開發(fā)中,常用的工具類,我們都會(huì)專門封裝起來進(jìn)行統(tǒng)一處理,方便以后統(tǒng)一調(diào)用、修改。網(wǎng)絡(luò)請(qǐng)求類算是用到最多...
    jzz_閱讀 1,162評(píng)論 2 3
  • fetch 返回的是一個(gè) Promise 對(duì)象, 每個(gè) promise 對(duì)象最后會(huì)有 resolve 或 re...
    lesliefang閱讀 3,477評(píng)論 0 0
  • 國外某網(wǎng)站給出了44道JS難題,試著做了下,只做對(duì)了17道。這些題涉及面非常廣,涵蓋JS原型、函數(shù)細(xì)節(jié)、強(qiáng)制轉(zhuǎn)換、...
    康斌閱讀 7,905評(píng)論 9 51
  • 1. 前言 前端圈有個(gè)“?!保涸诿嬖嚂r(shí),問個(gè)css的position屬性能刷掉一半人,其中不乏工作四五年的同學(xué)。在...
    YjWorld閱讀 4,941評(píng)論 5 15
  • ?記得《北京愛情故事》里,梁家輝和劉嘉玲扮演的一對(duì)夫妻,精心設(shè)計(jì)在圣托里尼島假扮偷情尋找刺激,紀(jì)念結(jié)婚20周年,彼...
    北京老炮兒閱讀 630評(píng)論 2 3

友情鏈接更多精彩內(nèi)容