JavaScript XMLHttpRequest


XMLHttpRequest는 JavaScript에서 비동기적으로 서버와 데이터를 주고받기 위해 사용하는 API입니다. 비록 현대적인 대안으로 fetch API가 등장했지만, 여전히 많은 기존 코드와 라이브러리에서 사용되고 있으며 브라우저의 호환성 측면에서 중요합니다.

1. XMLHttpRequest 개요

XMLHttpRequest 객체는 웹 페이지가 전체를 다시 로드하지 않고도 서버로부터 데이터를 요청할 수 있게 해줍니다. 이 기능은 AJAX(Asynchronous JavaScript and XML)의 핵심 부분입니다.

2. 기본 사용법

2.1 객체 생성

const xhr = new XMLHttpRequest();

2.2 요청 설정

open 메서드를 사용해 요청을 초기화합니다. 첫 번째 인수는 HTTP 메서드, 두 번째 인수는 요청 URL, 세 번째 인수는 비동기 여부(기본값: true)입니다.

xhr.open('GET', 'https://api.example.com/data', true);

2.3 요청 보내기

send 메서드를 사용해 요청을 서버로 보냅니다.

xhr.send();

3. 응답 처리

3.1 onreadystatechange 이벤트

onreadystatechange 이벤트 핸들러를 사용해 요청 상태 변화에 따른 처리를 할 수 있습니다. readyStatestatus를 사용해 요청 상태를 확인합니다.

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error('Request failed. Status:', xhr.status);
    }
  }
};

readyState의 값은 다음과 같습니다:

  • 0: UNSENTopen 메서드가 호출되지 않음
  • 1: OPENEDopen 메서드가 호출됨
  • 2: HEADERS_RECEIVEDsend 메서드가 호출됨
  • 3: LOADING – 요청이 처리 중이며, 일부 데이터가 수신됨
  • 4: DONE – 요청이 완료됨

3.2 responseType 설정

응답 타입을 설정할 수 있습니다. 기본값은 text입니다.

xhr.responseType = 'json';

4. HTTP 메서드 사용 예

4.1 GET 요청

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
    } else {
      console.error('Request failed. Status:', xhr.status);
    }
  }
};

xhr.send();

4.2 POST 요청

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
    } else {
      console.error('Request failed. Status:', xhr.status);
    }
  }
};

const data = JSON.stringify({ key1: 'value1', key2: 'value2' });
xhr.send(data);

5. 추가 설정 및 활용

5.1 요청 헤더 설정

setRequestHeader 메서드를 사용해 요청 헤더를 설정할 수 있습니다.

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer token');

5.2 비동기와 동기 요청

세 번째 인수로 false를 전달하면 동기 요청을 보낼 수 있습니다. 하지만 이는 페이지의 응답성을 떨어뜨릴 수 있으므로 주의해야 합니다.

xhr.open('GET', 'https://api.example.com/data', false);
xhr.send();
if (xhr.status === 200) {
  console.log(xhr.responseText);
}

5.3 응답 형식

응답 형식을 설정하여 다양한 타입의 데이터를 처리할 수 있습니다.

  • xhr.responseText: 문자열 형식의 응답 데이터
  • xhr.responseXML: XML 형식의 응답 데이터
  • xhr.response: 설정된 responseType에 따라 변하는 응답 데이터
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.response);
    } else {
      console.error('Request failed. Status:', xhr.status);
    }
  }
};

5.4 타임아웃 설정

timeout 속성을 사용해 요청에 타임아웃을 설정할 수 있습니다.

xhr.timeout = 5000; // 5초
xhr.ontimeout = function() {
  console.error('The request timed out.');
};

5.5 에러 처리

onerror 이벤트 핸들러를 사용해 네트워크 에러를 처리할 수 있습니다.

xhr.onerror = function() {
  console.error('Network error occurred.');
};

결론

XMLHttpRequest는 비동기 네트워크 요청을 처리하기 위한 강력한 도구입니다. 다양한 HTTP 메서드, 헤더 설정, 응답 형식 설정 등 다양한 기능을 제공하여 서버와 클라이언트 간의 통신을 효율적으로 처리할 수 있습니다. 비록 fetch API가 현대적인 대안으로 많이 사용되고 있지만, XMLHttpRequest는 여전히 유용한 기술로 자리잡고 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *