fetch, axios 비교

juno·2022년 8월 31일
0

통신

목록 보기
4/4

문법

1. fetch

	//문법
	fetch('url',{data})
    
    
    // json 형태 데이터 통신 기준 
    //get
    
    fetch('url').then(response=>response.json())
    .then(data => console.log(data))
    
    //Post 예시
    
    fetch('url',{
    	method: 'POST',
        headers: {
        'Content-Type': 'application/json'
        },
        bdoy: JSON.stringify({
        	data: '보내고 싶은거'
        })
    }).then(response=>response.json())
    .then(data=>console.log(data))
    

2. axios

axios 요청 방법

	1.  http 메서드 옵션에 붙이기
    
      axios('url', {
        // 설정 옵션
      });
      
      // Post 예시
      axios('url',{
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        bdoy: JSON.stringify({
          data: '보내고 싶은거'
      })
      
   2. 아래와 같이 HTTP 메서드를 붙일 수도 있습니다.
   
      // POST 통신

      axios.post(url, {
        headers: {
        	'Content-Type': 'application/json'
        },
        body: JSON.stringify({
        	data: '보내고싶은거'
      }).then(response=> console.log(response.data))
      
      
      

fetch와 axios의 차이

fetch

fetch()는 .then() 메서드에서 처리된 promise를 반환합니다. 이 때는 아직 우리가 필요한 JSON 데이터의 포맷이 아니기 때문에 응답 객체의 .json() 메서드를 호출합니다. 그러면 JSON 형식의 데이터로 이행(resolve)된 또 다른 promise를 반환합니다. 따라서 일반적인 fetch 요청은 두 개의 .then() 호출을 갖습니다.

axios

Axios를 사용하면 응답 데이터를 기본적으로 JSON 타입으로 사용할 수 있습니다. 응답 데이터는 언제나 응답 객체의 data 프로퍼티에서 사용할 수 있습니다.

자동 문자열 변환(stringify)

Axios가 자동으로 데이터를 문자열로 변환해줍니다.

const url = "https://jsonplaceholder.typicode.com/todos";

const todo = {
  title: "A new todo",
  completed: false,
};

axios
  .post(url, {
    headers: {
      "Content-Type": "application/json",
    },
    data: todo,
  })
  .then(console.log);

fetch일 경우 JSON.stringify로 문자열로 변환해야 한다.

const url = "https://jsonplaceholder.typicode.com/todos";

const todo = {
  title: "A new todo",
  completed: false,
};

fetch(url, {
    headers: {
      "Content-Type": "application/json",
    },
    data: JSON.stringify(todo),
  })
  .then(response=>response.json())
  .then(data=>console.log(data);
profile
안녕하세요 인터랙션한 웹 개발을 지향하는 프론트엔드 개발자 입니다. https://kimjunho97.tistory.com => 블로그 이전 중

0개의 댓글