fetch 단순 봉인

1744 단어
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

좋은 웹페이지 즐겨찾기