[JS] Axios

zzincode·2024년 7월 11일
0

JavaScript

목록 보기
20/24
post-thumbnail

Axios

Promise API를 활용하는 HTTP 비동기 통신 라이브러리

  • 요청을 보내기 전에 데이터를 변환하고, 응답을 받으면 자동으로 JSON으로 변환하기 때문에 한번의 .then()호출을 갖음
  • 400, 500대의 error발생시에 reject에 response를 전달해 catch로 잡아낼 수 있음
    fetch의 경우 네트워크 장애나 요청이 완료되지 않은 경우만 response를 전달하기 때문에 나머지의 경우는 따로 예외처리를 시켜줘야함

설치

npm install axios

예시

import axios from 'axios';

// GET 요청
axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

// POST 요청
axios.post('https://jsonplaceholder.typicode.com/todos', {
  userId: 1,
  title: 'New Todo',
  completed: false
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

// PATCH 요청
axios.patch('https://jsonplaceholder.typicode.com/todos/1', {
  completed: true
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

// DELETE 요청
axios.delete('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

API 관련해서 계속해서 공부해야지 하다가
프로젝트를 진행하며 적용시켜보면서 공부할 수 있는 기회가 되었다.
그동안은 그냥 공식처럼 사용했던 거 같은데 이번 기회에 제대로 동작하는 방식을 제대로 이해할 수 있는 기회가 되어 다행이다..

0개의 댓글