728x90
728x90
Axios 라이브러리
들어가며
- Axios 라이브러리에 대해 알아보자.

Axios
개념
- Node.js 및 브라우저에서 동작하는 HTTP 클라이언트 라이브러리 중 하나
- 주로 HTTP 요청(Request)을 생성하고 응답(Response)을 처리하는 데 사용된다.
- Axios는 Promise 기반으로 작성되어 있어 비동기 코드를 쉽게 다룰 수 있다.
- 동일한 코드베이스로 브라우저와 Node.js에서 실행할 수 있다.
- 서버 단(Server-Side)에서는 네이티브 Node.js의
http
모듈을 사용하고, 클라이언트(브라우저)에서는XMLHttpRequests
를 사용한다. - Axios를 사용하면 HTTP 요청을 쉽게 생성하고 응답을 처리할 수 있다.
- 특히 비동기 프로그래밍에서 Promise를 사용하므로 코드가 더 읽기 쉽고 유지보수가 쉽다.
Axios를 사용하지 않을 경우
import https from "https"; app.get("/", (req, res) => { const options = { hostname: "dev-astra.com", path: "/random", method: "GET", }; const request = https.request(options, (response) => { let data = ""; response.on("data", (chunk) => { data += chunk; }); response.on("end", () => { try { const result = JSON.parse(data); res.render("index.ejs", {activity: data}); } catch (error) { console.error("Failed to parse response:", error.message); res.status(500).send("Failed to fetch activity. Please try again."); } }); }); request.on("error", (error) => { console.error("Failed to make request:", error.message); res.status(500).send("Failed to fetch activity. Please try again."); }); request.end(); });
Axios를 사용할 경우
- Axios를 사용하지 않을 경우의 코드에서
const options
부분과const request
부분을const response = await axios.get("https://dev-astra.com/random");
코드 한 줄로 표현할 수 있다.
import axios from "axios"; application.get("/", async (req, res) => { try { const response = await axios.get("https://dev-astra.com/random"); res.render("index.ejs", { activity: response.data }); } catch (error) { console.error("Failed to make request:", error.message); res.status(500).send("Failed to fetch activity. Please try again."); } });
특징
① Promise 기반
- 자바스크립트의 Promise를 사용하여 비동기적으로 HTTP 요청을 처리한다.
- 이를 통해 코드를 간결하게 작성하고, 에러 핸들링을 쉽게 할 수 있다.
Promise
- 자바스크립트의 Promise는 비동기 코드를 더 쉽게 다룰 수 있도록 하는 객체이다.
- 비동기 작업은 주로 네트워크 요청, 파일 읽기, 타이머 등의 작업을 의미하며, 이러한 작업은 시간이 지연될 수 있기 때문에 프로그램의 흐름을 차단하지 않고 계속해서 다른 작업을 수행할 수 있도록 한다.
- Promise는 일반적으로 다음과 같은 상태를 갖는다.
✅ 대기(Pending)
- 초기 상태
- 비동기 작업이 완료되거나 거부될 때까지 계속된다.
✅ 이행(Fulfilled)
- 비동기 작업이 성공적으로 완료되었을 때의 상태
- 결과값과 함께 이행된다.
✅ 거부(Rejected)
- 비동기 작업이 실패했을 때의 상태
- 오류 정보와 함께 거부된다.
- Promise는 일반적으로 다음과 같이 사용된다.
const myPromise = new Promise((resolve, reject) => { // 비동기 작업 수행 // 성공 시 resolve() 호출, 실패 시 reject() 호출 if (/* 비동기 작업 성공 조건 */) { resolve('성공했습니다!'); } else { reject('실패했습니다!'); } }); // Promise의 상태에 따라 처리 myPromise .then((result) => { console.log('이행됨:', result); }) .catch((error) => { console.error('거부됨:', error); });
- 위의 코드에서
then
은 Promise가 이행됐을 때 호출되고,catch
는 Promise가 거부됐을 때 호출된다. - 이러한 구조를 통해 비동기 코드를 더 직관적이고 관리하기 쉽게 작성할 수 있다.
- 또한, 여러 Promise를 조합하거나 순차적으로 실행하는 등의 복잡한 비동기 흐름을 간편하게 다룰 수 있도록 하는 여러 유틸리티 함수들도 Promise 객체와 함께 제공된다.
② 브라우저 및 서버 측에서 사용 가능
- 브라우저와 Node.js 환경에서 모두 사용 가능하므로, 클라이언트 측 및 서버 측 코드에서 동일한 HTTP 클라이언트를 사용할 수 있다.
③ 요청 및 응답 변형
- Axios는 요청과 응답을 변형할 수 있는 기능을 제공하여 데이터를 쉽게 가공할 수 있다.
④ 자동 변환 및 직렬화
- JSON 데이터의 자동 변환 및 직렬화를 지원하여 개발자가 명시적으로 변환 작업을 수행하지 않아도 된다.
⑤ 기타
- 이외에도 다음과 같은 특징이 있다.
- 브라우저를 위해 XMLHttpRequests 생성
- 요청 및 응답 인터셉트
- 요청 취소
- JSON 데이터 자동 변환
- XSRF를 막기위한 클라이언트 사이드 지원
설치
$ npm install axios
사용 예
기본적인 사용 예
const axios = require('axios'); // GET 요청 axios.get('https://api.example.com/data') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); // POST 요청 axios.post('https://api.example.com/data', { key: 'value' }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
구성 설정 예
// 기본 설정 axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = 'Bearer TOKEN'; // 인스턴스 생성 및 사용자 지정 설정 const instance = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, headers: {'X-Custom-Header': 'value'} }); // 사용자 지정 설정을 사용한 GET 요청 instance.get('/data') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
참고
시작하기 | Axios Docs
시작하기 브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리 Axios란? Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코
axios-http.com
axios
Promise based HTTP client for the browser and node.js. Latest version: 1.6.2, last published: 5 hours ago. Start using axios in your project by running . There are 112268 other projects in the npm registry using axios.
www.npmjs.com
728x90
728x90
'Programming > Axios' 카테고리의 다른 글
[Axios] 헤더에 인증 정보 추가하는 방법 (1) | 2024.11.14 |
---|---|
[Axios] HTTP 메서드 (1) | 2024.09.21 |
[Axios] 전역(Global)/커스텀(Custom) 인스턴스, 인터셉터(Interceptor) (0) | 2024.09.20 |