fetch와 axios 모듈화 예제
본문 바로가기

Network&etc/HTTP

fetch와 axios 모듈화 예제

fetch

특징: axios에 비해 header와 body에 처리가 필요함(옵션이라던지 제이슨처리 등). 자바스크립트에서 제공해줌, 과거에는 인터넷익스플로어에서는 미지원한다했는데 요새는..?

export const fetchPost = async(url, requestBody) =>{
    return await fetch(url, {
            method : "POST",
            headers: { 'Content-Type': 'application/json; charset=utf-8', 'dataType': 'json', },
            body: JSON.stringify(requestBody)
    })
}

//fetchGet

//fetchPut

//fetchDelete

//통신 상태 처리
export const checkStatusAndParse = response => {
 if(response.error === true) throw new Error(`Status Code Error, ${response.status}`)
 return response.json()
}
const requestBody = {
    email:state.email,
    password:state.password,
}
const login = data => {
    console.log(data)
}
        
fetchPost(`http://localhost:3000/user/login`,requestBody)
        .then(checkStatusAndParse)
        axios.post("http://localhost:3000/user/login",requestBody)
        .then(login)
        .catch(error => console.log(error))

 

axios

라이브러리로 브라우저 호환성이 좋음. fetch에 비해 따로 처리해주지않아도되서 간편함.

https://www.npmjs.com/package/axios

 

axios

Promise based HTTP client for the browser and node.js. Latest version: 0.26.0, last published: 14 days ago. Start using axios in your project by running `npm i axios`. There are 72274 other projects in the npm registry using axios.

www.npmjs.com

axios.post(...)혹은 axios({method:'post',...}) 두가지 방법이 있는데 나같은 경우는 모듈화를 해야해서 후자의 것을 하기로했다.

axios({
    method:'POST',
    url:'http://localhost:3000/user/login',
    data:requestBody
})
import axios from "axios"

//404
const onNotFound = (err) => {
    throw new Error(`Status Code Error, ${err.status}, ${err.msg}`)
}

//500
// const onServerError = (err) =>{
//     throw new Error(`Status Code Error, ${err.status}, ${err.msg}`)
// }

const onCatchProcess = (data) => {
    if(data.status === 404) onNotFound(data)
    // else if(data.status === 500) onServerError(data)
    return data
}

const axiosWrapper = (method, url, data) => {
    return axios({
        method,
        url,
        data,
    })
    .then((res)=>res.data)
    .then(data => onCatchProcess(data))
    .catch((err) =>console.log(err))
}

export default axiosWrapper

 

https://bravenamme.github.io/2021/11/04/api-wrapper/

 

브라우저에서 비동기요청을 수행할 때 도움이 될 수도 있는 글 (api wrapping)

API 서버와의 통신 웹 개발 환경이 여러모로 다양해지면서 REST API 서버를 별도로 두고 클라이언트(브라우저)에서 특정 endpoint를 호출해 CRUD를 수행하는 모델이 속속 등장하고 있습니다. 이러한 개

bravenamme.github.io

 

반응형