기록
article thumbnail
728x90

XMLHttpRequest

  • 콜백 기반 API
  • 서버와 상호작용할 때 많이 사용하며 비동기식 또는 동기식의 두 가지 방법으로 데이터를 가져올 수 있습니다. 다만 동기식 XHR 요청은 네트워크 상태가 좋지 않거나 원격 서버의 응답이 느린 경우 웹에서 중단을 일으키는 경우가 많아 사용하지 않습니다.
  • XML뿐만 아니라 HTML, binary 등 모든 종류의 데이터를 가져올 수 있습니다.
    
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "/bar/foo.txt", true); // true : 비동기식 fasle: 동기
    xhr.onload = (e) => {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      } else {
        console.error(xhr.statusText);
      }
    }
    };
    xhr.onerror = (e) => {
    console.error(xhr.statusText);
    };
    xhr.send(null);
    
    

> open() 요청을 호출하기 전에 이벤트 리스너를 추가해야 합니다.

Fetch

  • Promise 기반으로, fetch() 메서드로 네트워크의 리소스를 쉽게 비동기적으로 가져올 수 있습니다.
  • CORS를 포함한 최신 웹 표준 기능을 제공합니다.
  • 간단하고 일관된 메서드 체이닝 방식을 사용하여 요청 및 응답 처리를 관리하며 요청과 응답은 Response 객체로 처리됩니다.
    
    // POST 메서드 구현 예제
    async function postData(url = "", data = {}) {
    // 옵션 기본 값은 *로 강조
    const response = await fetch(url, {
      method: "POST", // *GET, POST, PUT, DELETE 등
      mode: "cors", // no-cors, *cors, same-origin
      cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
      credentials: "same-origin", // include, *same-origin, omit
      headers: {
        "Content-Type": "application/json",
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      redirect: "follow", // manual, *follow, error
      referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
    });
    return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
    }
    
    postData("https://example.com/answer", { answer: 42 }).then((data) => {
    console.log(data); // JSON 데이터가 data.json() 호출에 의해 파싱됨
    });

모두 Ajax 요청과 데이터 검색, 업데이트, 백엔드 서비스 통합 등 서버와 통신하고 데이터를 가져오는 데 주로 사용됩니다. Fetch API가 더 최신으로 HTTP 확장된 개념과 브라우저 및 최신 환경에서 XHR API 보다 선호하고 있습니다.

참고 자료
mdn :
https://developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

728x90