axios

이진욱·2024년 10월 11일

이론

목록 보기
1/24

axios는 브라우저와 Node.js 환경에서 모두 사용할 수 있는 자바스크립트 HTTP 클라이언트 라이브러리입니다. 주로 API 요청을 보내고, 서버와 클라이언트 간의 비동기 HTTP 요청을 처리하는 데 사용됩니다.

주요 특징

  • Promise 기반: axios는 Promise 기반으로 작성되어 비동기적으로 작동하며, async/await 구문과 함께 사용하기 편리합니다.
  • 간편한 HTTP 요청: axios는 GET, POST, PUT, DELETE 등의 HTTP 메서드 요청을 간편하게 사용할 수 있도록 메서드를 제공합니다.
  • JSON 자동 변환: 요청 및 응답에서 JSON 데이터 처리를 자동으로 지원하므로 JSON 문자열을 수동으로 파싱하거나 직렬화할 필요가 없습니다.
  • 응답 데이터 변환: 응답 데이터를 자동으로 변환할 수 있으며, 필요에 따라 커스터마이징할 수 있습니다.
    요청 취소: 요청을 보내기 전이나 중간에 취소할 수 있도록 기능을 제공합니다.
  • 인터셉터 기능: 요청 및 응답에 인터셉터를 추가하여 전처리나 후처리를 쉽게 할 수 있습니다. 예를 들어, 모든 요청에 공통적으로 사용할 헤더를 추가하거나, 응답 데이터를 로깅할 수 있습니다.
  • 브라우저 지원 및 보안: 브라우저 환경에서 XSRF (Cross-Site Request Forgery) 보호 기능을 제공합니다.

설치

npm을 사용하는 경우
npm install axios

yarn을 사용하는 경우
yarn add axios

기본 사용법

1. GET 요청

GET 요청은 서버로부터 데이터를 받아올 때 사용된다

import axios from 'axios';


axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data); // 응답 데이터를 출력합니다.
})
.catch(error => {
console.error("Error fetching data", error);
});

2. POST 요청

POST 요청은 서버에 데이터를 보낼 때 주로 사용됩니다. 예를 들어, 사용자 로그인이나 데이터 등록 등을 할 때 유용합니다.

import axios from 'axios';


const data = {
username: 'testuser',
password: 'password123'
};


axios.post('https://api.example.com/login', data)
.then(response => {
console.log(response.data); // 응답 데이터를 출력합니다.
})
.catch(error => {
console.error("Error posting data", error);
});

3. async/await 구문 사용

async/await를 통해 비동기 호출을 더 간단하게 관리할 수 있습니다.

import axios from 'axios';


async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data); // 응답 데이터를 출력합니다.
} catch (error) {
console.error("Error fetching data", error);
}
}


fetchData();

고급 기능

1. 요청 인터셉터

모든 요청에 공통적으로 헤더를 추가하거나 로깅하는 등의 작업을 할 수 있습니다.

axios.interceptors.request.use(
config => {
config.headers.Authorization = 'Bearer your_token';
console.log('Request sent at: ', new Date());
return config;
},
error => {
return Promise.reject(error);
}
);

2. 응답 인터셉터

응답 데이터를 전처리하거나 에러를 로깅할 수 있습니다.

axios.interceptors.response.use(
response => {
// 응답 데이터 전처리
return response;
},
error => {
console.error('Error occurred:', error);
return Promise.reject(error);
}
);

3. 요청 취소

특정 요청이 불필요해졌거나 취소해야 할 경우에 사용할 수 있습니다.

const CancelToken = axios.CancelToken;
let cancel;


axios.get('/some_endpoint', {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
});


// 요청을 취소하고 싶을 때
cancel();

자료 참고 : ChatGPT

profile
열심히 하는 신입 개발자

0개의 댓글