본문 바로가기
FrontEnd/JavaScript

Axios에 대하여 (vs Fetch)

by 위그든씨 2022. 12. 7.

무엇을 선택할까?

결론적으로 말하자면 개발 환경에 따라 다르겠지만 React 프로젝트를 진행할경우 Axios 를 선호하는 경향이 있다고 한다.

Axios는 크로스 브라우징에 신경을 많이 쓴 모듈이고 기능또한 우수하기 때문. 어떻게보면 fetch의 상위 호환

  • Axios 장단점
    • 장점
      1. response timeout 처리 방법이 있다 (fetch 에는 x) 
      2. promise 기반이라 다루기 쉽다
      3. 크로스 브라우징에 신경을 많이 써서 브라우저 호환성 뛰어남
    • 단점
      • 모듈 설치를 해줘야한다. 
  • Fetch 장단점
    • 장점
      1. 내장 라이브러리여서 별도의 import 및 설치 x
      2. promise 기반
      3. 프레임워크가 불안정할때 사용하기 좋다 (내장 라이브러리이니까)
    • 단점
      1. internet Exporloer의 경우에 fetch를 지원하지 않는 버전도 존재
      2. 기능이 부족함
    • Fetch에 대한 자세한건 이곳 클릭

Axios 문법

axios(url, {
  // 설정 옵션
});
axios.get(url, {
  // 설정 옵션
});
axios(url);
//HTTP 메서드 없이 요청할 경우 기본 GET 요청
axios({
	method:"post",
    url: '/user/1234',
    data:{
    	firstName: 'young',
        lastName: 'Kim',
	}
});
axios(url, {
  method: "get", // 다른 옵션도 가능합니다 (post, put, delete, etc.)
  headers: {},
  data: {},
});
  • Axios를 사용해서 데이터를 긁어오면 기본적으로 JSON타입으로 사용 가능함 (Fetch와의 차이점) 
  • 응답 데이터는 언제나 응답 객체의 data 프로퍼티에서 사용 가능
const url = "https://jsonplaceholder.typicode.com/todos";

axios.get(url).then((response) => console.log(response.data));

 

에러 처리

기본적으로 promise를 반환하기 때문에 reject 된다면 .catch()를 사용하여 에러 처리 가능

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

axios
  .get(url)
  .then((response) => console.log(response.data))
  .catch((err) => {
    console.log(err.message);
  });
// POST
axios.post('/api/todos', { title: 'ajax 공부' }).then((res) => {
    console.log(res);
});

// PATCH
axios.patch('/api/todos/3', { title: 'axios 공부' }).then((res) => {
    console.log(res);
});

// DELETE /api/todos/1 (Delete)
// DELETE
axios.delete('/api/todos/3').then((res) => {
    console.log(res);
});


// GET
axios.get('/api/todos').then((res) => {
    console.log(res.data);
});

or;

const result = await axios.get('/api/todos');
console.log(result.data);

//axios 요청 메소드의 두 번째 인자로 config 객체를 넘길 수 있습니다

// config 객체
axios
    .get('/api/todos', {
        params: {
            // query string
            title: 'NEXT JS',
        },
        headers: {
            // 요청 헤더
            'X-Api-Key': 'my-api-key',
        },
        timeout: 3000, // 1초 이내에 응답이 오지 않으면 에러로 간주
    })
    .then((res) => {
        console.log(res);
    });

참고 : https://velog.io/@eunbinn/Axios-vs-Fetch