페이지 내 에서 발생되는 XHR Response를 모니터링 하는 방법

두가지 방법을 소개하고자한다.

XHRHttpRequest 선언시 EventHandler에 등록하는 방법

const xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  // In local files, status is 0 upon success in Mozilla Firefox
  if(xhr.readyState === XMLHttpRequest.DONE) {
    var status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request has been completed successfully
      console.log(xhr.responseText);
    } else {
      // Oh no! There has been an error with the request!
    }
  }
};
xhr.send();
//출처
//https://wiki.developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest/onreadystatechange

이 방법은 XHR을 선언하면서 이벤트 등록을 통해 해당 xhr의 이벤트롤 콘솔로 감시할수 있습니다.

XHRHttpRequest 를 재정의 하는 방법

let oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
    this.addEventListener('load', function() {
        console.log(this.response);
    });
    return oldXHROpen.apply(this, arguments);
}

 

'WEB > JS' 카테고리의 다른 글

XMLHttpRequest(XHR) 란 무엇인가.  (0) 2020.10.06

XHR은 무엇일까?

XHR은 XMLHttpRequest의 약자로 말 그대로 http 프로토콜을 통해 서버에 자원을 요청하기 위해 사용한다.

페이지 전체를 새로고침 할 필요 없이 원하는 데이터를 url에서 제공받을 수 있다.

대표적인 예로 Ajax가 있다.

Methods

  • abort이미 전송된 request를 중단
  • getAllResponseHeaders모든 ResponseHeader를 문자열로 반환합니다. response가 없는경우는 null 을 반환합니다.
  • getResponseHeader(headerName)header의 값들 중 해당하는 입력으로 들어온 이름과 일치하는 값을 반환합니다.
  • open(method, url[, async[, user[, password]]])request를 초기화 합니다
    url, 요청방법, 비동기 여부, 인증목적의 user, password 등을 포함합니다
  • send(body)
    request를 서버에 보냅니다.
    Document, Blob, BufferSource, FormData, URLSerchParams, USVString 등이 포함될 수 있습니다.
  • setRequestHeader(header, value)
    request header의 값을 지정합니다.
    open 과 send 사이에 call해야하며, 여러번 call할시에는 기존의 header's content에 더해지게 됩니다.

Example

 

5) Spring - 회원가입(ajax를 이용한 id 중복체크)

json을 이용하기 위한 lib 추가 pom.xml에 아래 코드를 추가해 줍니다. com.googlecode.json-simple json-simple 1.1 org.codehaus.jackson jackson-mapper-asl 1.9.13 Register.jsp 수정 ajax를 이용하기위해 jqu..

migusdn.tistory.com

에서 Jquery를 이용한 ajax를 XMLHttpRequest로 바꿔보겠다.

//Jquery

id = $("#user_id").val();
	
$.ajax({
    url: 'ID_Check',
    type: 'POST',
    dataType: 'text', //서버로부터 내가 받는 데이터의 타입
    contentType : 'text/plain; charset=utf-8;',//내가 서버로 보내는 데이터의 타입
    data: id ,
    success: function(data){
         if(data == 0){
         console.log("아이디 없음");
         alert("사용하실 수 있는 아이디입니다.");
         }else{
         	console.log("아이디 있음");
         	alert("중복된 아이디가 존재합니다.");
         }
    },
 });
 
//XMLHttpRequest

const id = document.getElementById("user_id").val();

var checkRequest = new XMLHttpRequest();

checkRequest.onload = function(){
	if(checkRequest.status === 200 || checkRequest.status === 201) {
		if(checkRequest.responseText == 0){
			console.log("아이디 없음");
			alert("사용하실 수 있는 아이디입니다.");
		} else {
			console.log("아이디 있음");
			alert("중복된 아이디가 존재합니다.");
		} 
	} else {
		console.log("error");
	}
};

checkRequest.open("POST", "ID_Check");
checkRequest.setRequestHeader("Content-Type", "text/plain; charset=utf-8;");
checkRequest.setRequestHeader("dataType", "text");
checkRequest.send(id);

출처: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest, https://xhr.spec.whatwg.org/

'WEB > JS' 카테고리의 다른 글

XHR response Monitering  (0) 2020.11.07

+ Recent posts