美文网首页
fetch简单封装

fetch简单封装

作者: madisn | 来源:发表于2018-11-12 15:49 被阅读15次
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,不传默认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

相关文章

网友评论

      本文标题:fetch简单封装

      本文链接:https://www.haomeiwen.com/subject/vwdcfqtx.html