// XMLHttpRequest 객체 생성 const xhr = newXMLHttpRequest();
// HTTP 요청 초기화 xhr.open('GET', '/users');
// HTTP 요청 헤더 설정 // 클라이언트가 서버로 전송할 데이터의 MIME 타입 지정: json xhr.setRequestHeader('content-type', 'application/json');
// HTTP 요청 전송 xhr.send();
// readystatechange 이벤트는 HTTP 요청의 현재 상태를 나타내는 readyState 프로퍼티가 변경될 때마다 발생한다. xhr.onreadystatechange = () => { // readyState 프로퍼티는 HTTP 요청의 현재 상태를 나타낸다. // readyState 프로퍼티 값이 4(XMLHttpRequest.DONE)가 아니면 서버 응답이 완료되지 상태다. // 만약 서버 응답이 아직 완료되지 않았다면 아무런 처리를 하지 않는다. if (xhr.readyState !== XMLHttpRequest.DONE) return;
// 정상적으로 응답된 상태라면 response 프로퍼티에 서버의 응답 결과가 담겨 있다. if (xhr.status === 200) { console.log(JSON.parse(xhr.response)); } else { console.error('Error', xhr.status, xhr.statusText); } };
1 2 3 4 5 6 7 8 9 10 11 12
// XMLHttpRequest 객체 생성 const xhr = newXMLHttpRequest();
// HTTP 요청 초기화 xhr.open('POST', '/users');
// HTTP 요청 헤더 설정 // 클라이언트가 서버로 전송할 데이터의 MIME 타입 지정: json xhr.setRequestHeader('content-type', 'application/json');