hanker

[JavaScript] 여러가지 비동기 HTTP 통신 모듈 본문

JavaScript

[JavaScript] 여러가지 비동기 HTTP 통신 모듈

hanker 2025. 6. 1. 14:54
반응형

JavaScript에서 서버와 데이터를 주고받는 비동기 통신 방법들을 알아보자.

 


1. XMLHttpRequest

 

XMLHttpRequest는 JavaScript에서 비동기 HTTP 요청을 보내는 가장 기본적인 방법이다.

모든 브라우저에서 지원된다.

 

 라이브러리 추가 필요: 없음

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        const data = JSON.parse(xhr.responseText);
        console.log(data);
    }
};
xhr.send();
  • 장점: 모든 브라우저 지원, 외부 의존성 없음
  • 단점: 복잡한 문법, 콜백 지옥 가능성

 


2. jQuery AJAX

 

jQuery는DOM 조작과 AJAX 통신을 간편하게 만든 JavaScript 라이브러이디ㅏ.

$.ajax() 메서드로 XMLHttpRequest를 더 쉽게 사용할 수 있다.

 

라이브러리 추가 필요 (jQuery)

$.ajax({
    url: 'https://api.example.com/data',
    method: 'GET',
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    error: function(xhr, status, error) {
        console.error('에러 발생:', error);
    }
});

// 더 간단한 방법들
$.get('https://api.example.com/data', function(data) {
    console.log(data);
});

$.post('https://api.example.com/users', { name: '홍길동' }, function(response) {
    console.log(response);
});
  • 장점: 간단한 문법, 크로스브라우저 호환성, 다양한 유틸리티 함수
  • 단점: jQuery 전체 라이브러리 로드 필요, 모던 개발에서는 과도한 의존성

 


3. Fetch API

 

Fetch API는 ES6와 함께 도입된 모던 JavaScript의 네트워크 요청 인터페이스이다.

Promise 기반으로 작동하며 더 깔끔한 비동기 코드를 작성할 수 있다.

 

라이브러리 추가 필요: 없음

// Promise 방식
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('네트워크 응답이 실패했습니다');
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('에러:', error));

// async/await 방식
async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        if (!response.ok) {
            throw new Error('네트워크 응답이 실패했습니다');
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('에러:', error);
    }
}

// POST 요청
fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: '홍길동' })
})
.then(response => response.json())
.then(data => console.log(data));
  • 장점: 모던 문법, Promise 기반, 외부 의존성 없음
  • 단점: 구형 브라우저 미지원 (IE), 에러 처리가 복잡할 수 있음

 


4. Axios

 

Axios는 Promise 기반의 HTTP 클라이언트 라이브러리로, 브라우저와 Node.js 환경에서 모두 사용할 수 있다.

 

라이브러리 추가 필요: Axios

// GET 요청
axios.get('https://api.example.com/data')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('에러:', error);
    });

// async/await 방식
async function fetchData() {
    try {
        const response = await axios.get('https://api.example.com/data');
        console.log(response.data);
    } catch (error) {
        console.error('에러:', error);
    }
}

// POST 요청
axios.post('https://api.example.com/users', {
    name: '홍길동',
    email: 'hong@example.com'
})
.then(response => {
    console.log(response.data);
});

// 설정 객체로 요청
axios({
    method: 'put',
    url: 'https://api.example.com/users/1',
    data: {
        name: '김철수'
    },
    headers: {
        'Authorization': 'Bearer token123'
    }
});

// 인터셉터 설정
axios.interceptors.request.use(
    config => {
        config.headers.Authorization = `Bearer ${getToken()}`;
        return config;
    },
    error => Promise.reject(error)
);
  • 장점: 풍부한 기능, 인터셉터 지원, 자동 JSON 파싱, 요청/응답 변환
  • 단점: 추가 라이브러리 필요, 번들 크기 증가

 


정리

 

  • 신규 프로젝트: Fetch API 또는 Axios
  • 레거시 프로젝트: 기존 jQuery 사용 중이면 jQuery AJAX 유지
  • 단순한 요청: Fetch API면 충분
  • 복잡한 HTTP 통신: Axios의 기능 활용
반응형