WEB/JavsScript

[JavaScript] XMLHttpRequest

Raymond 2022. 5. 26. 20:57

XMLHttpRequest


XMLHttpRequestJavaScript에서 HTTP 요청을 할 수 있는 내장 브라우저 객체입니다. 현재는 ES6에 나온 fetch를 쓰는 더 좋은 방법이 있습니다. 하지만 윈도우 익스플로어에서는 fetch사용 불가.

 

1. XMLHttpRequest 객체를 생성

비동기 통신을 하기 위하여 사용. 동기통신도 가능.

const xhr = new XMLHttpRequest();

 

2. xhr.open()

서버에서 정보를 얻어기 위하여 사용

method(GET, POST, PUT, DELETE) : 리소스 요청, 생성, 수정, 삭제
URL : 요청할 URL, 문자열은 URL 객체일 수 있습니다.

xhr.open("GET", "http://localhost:3000/posts"); // (method, url)

 

3. xhr.setRequestHeader(header, value)

HTTP요청 헤더의 값을 설정. 반드시 open()뒤에 호출하여야 하며, 또한 send()가 호출되기 전에 호출해야 합니다.

웹사이트 헤더 보는법

▶ content-type이란? : Content-Type 개체 헤더는 리소스의 media type을 나타내기 위해 사용됩니다.
ref) https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/Content-Type

▶ media type이란? : 과거에는 MIME type으로 불렸지만 지금은 "media type"으로 사용한다.

▶ mime의 종류는 다음 사이트에서 볼 수 있다. -> 이곳에 application/json이 나온다.
ref) https://www.iana.org/assignments/media-types/media-types.xhtml
xhr.setRequestHeader("content-type", "application/json");

 

4. xhr.send()

send()는 요청을 서버로 보냅니다. 실제로 http통신이 일어날때 body라는 곳에 데이터가 실려서 나가게된다.

xhr.send();

 

5. xhr.onload()

통신이 완료되어 데이터를 다 받아온 경우, 실행된다.

xhr.response : 응답값이 string으로 온다.

xhr.status : 읽기 전용 속성은 의 응답 에 XMLHttpRequest.status대한 숫자 HTTP 상태 코드 를 반환합니다.

xhr.statusText : 읽기 전용 XMLHttpRequest.statusText속성은 DOMStringHTTP 서버에서 반환한 응답의 상태 메시지를 포함하는 를 반환합니다. XMLHTTPRequest.status숫자 상태 코드를 나타내는 것과 달리 이 속성에는 "OK" 또는 "Not Found"와 같은 응답 상태 텍스트 가 포함됩니다.

xhr.onload = () => {
  if (xhr.status === 200) {
    const res = JSON.parse(xhr.response);
    // console.log(response);
    console.log(res);
    // callbackFunc(res);

    // 여기에 post 데이터를 가져와서 처리해야 하는 로직을 구현해야 함
    // return res;
  } else {
    console.log(xhr.status, xhr.statusText);
  }
};

status & statusText & xhr.response & typeof xhr.response

 

GET

function getData() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "http://localhost:3000/posts");
  xhr.setRequestHeader("content-type", "application/json");
  xhr.send();

  // 서버로 부터 응답을 받으면 실행
  xhr.onload = () => {
    if (xhr.status === 200) {
      const res = JSON.parse(xhr.response);
      console.log(res);
      // 응답받은 데이터를 처리하는 로직 구현해야하는 위치
    } else {
      console.log(xhr.status, xhr.statusText);
    }
  };
}

 

PUT

function putData() {
  const xhr = new XMLHttpRequest();
  xhr.open("PUT", "http://localhost:3000/posts/2");
  xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
  const data = { title: "HTML", author: "John Doe" };
  xhr.send(JSON.stringify(data));

  xhr.onload = () => {
    if (xhr.status === 200) {
      const res = JSON.parse(xhr.response);
      console.log(res);
    } else {
      console.log(xhr.status, xhr.statusText);
    }
  };
}

 

POST

function postData() {
  const xhr = new XMLHttpRequest();
  xhr.open("POST", "http://localhost:3000/posts");
  xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
  const data = { title: "JavaScript", author: "Jeremy" };
  xhr.send(JSON.stringify(data));

  xhr.onload = () => {
    if (xhr.status === 201) {
      const res = JSON.parse(xhr.response);
      console.log(res);
    } else {
      console.log(xhr.status, xhr.statusText);
    }
  };
}

 

DELETE

function deleteData() {
  const xhr = new XMLHttpRequest();
  xhr.open("DELETE", "http://localhost:3000/posts/2"); 
  // 삭제할데이터의 id를 마지막에 넣어주는것이 json-server의 규칙
  xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
  xhr.send();

  xhr.onload = () => {
    if (xhr.status === 200) {
      const res = JSON.parse(xhr.response);
      console.log(res);
    } else {
      console.log(xhr.status, xhr.statusText);
    }
  };
}

 

참고자료

https://ko.javascript.info/xmlhttprequest