Axios

브라우저와 Node.js에서 모두 사용 가능한 Promise 기반의 HTTP 클라이언트

API 요청을 보내거나 데이터를 주고받는 작업에 사용

XMLHttpRequest를 기반으로 동작

간결한 문법과 비동기적 작업 처리에 유용하여 많이 사용

GET, POST, PUT, DELETE 등의 HTTP 요청을 쉽게 보낼 수 있고, 응답 처리도 간단하다.

 

설치 명령어

//npm
npm install axios

//yarn
yarn add axios

 

예시

1. GET요청

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

GET 요청을 보내 특정 URL에서 데이터를 가져오기

응답(response)의 data 속성에 요청된 데이터가 담겨있다.

 

2. POST요청

import axios from 'axios';

axios.post('https://jsonplaceholder.typicode.com/posts', {
  title: 'New Post',
  body: 'This is a new post.',
  userId: 1
})
  .then(response => {
    console.log('Data posted:', response.data);
  })
  .catch(error => {
    console.error('Error posting data:', error);
  });

POST 요청을 통해 서버에 데이터를 전송하기

title, body, userId 등의 데이터를 서버에 전달하고, 서버에서 반환한 응답을 response.data로 확인

 

3. 비동기 함수

import axios from 'axios';

async function fetchData() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();

TypeScript의 async/await 문법을 사용

async/await를 사용하면 then과 catch 대신 보다 직관적인 방식으로 비동기 작업을 처리

+ Recent posts