프론트엔드

Fetch 와 Axios 어떤걸 써야될까?

말감78 2023. 3. 29. 10:54
반응형

● 둘다 js 에서 비동기 HTTP 통신을 할때 사용됨 

 

●Axios 는 Promise based HTTP client for the browser and node.js

즉, node.js와 브라우저를 위한 HTTP통신 라이브러리
비동기로 HTTP 통신을 가능하게 해주며 return을 promise 객체로 해주기 때문에 response 데이터를 다루기도 쉽다

 

Axios의 post method 구현

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Yongseong',
    lastName: 'Kim'
  }
});

 

● Fetch

fetch는 ES6부터 JavaScript의 내장 라이브러리로 들어왔습니다.
promise기반으로 만들어졌기에 Axios와 마찬가지로 데이터를 다루는데 어렵지 않으며, 내장 라이브러리라는 장점으로 인해 상당히 편리하고, 코드 또한 간단

 

Fetch의 post method 구현

 

//fetch
const url ='http://localhost3000/test`
const option ={
   method:'POST',
   header:{
     'Accept':'application/json',
     'Content-Type':'application/json';charset=UTP-8'
  },
  body:JSON.stringify({
  	name:'sewon',
    	age:20
  })

  fetch(url,options)
  	.then(response => console.log(response))

웹 프론트 프레임워크(react, vue)에서는 Axios를 선호하는 경향

 

아직 안정적이지 않은 프레임워크에서는 Fetch 사용하는게 좋은거 같다

 

●출처 https://velog.io/@kysung95/%EA%B0%9C%EB%B0%9C%EC%83%81%EC%8B%9D-Ajax%EC%99%80-Axios-%EA%B7%B8%EB%A6%AC%EA%B3%A0-fetch

반응형