XMLHttpRequest

Often abbreviated to XHR.
XMLHttpRequest supports both synchronous and asynchronous communications.
This object can retrieve data in any format from a server. It's not just limited to XML.


let url = 'https://api.github.com/users/officeaddins/repos';  

var options = {
  method: "GET",
  headers: {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': '.NET Foundation Repository Reporter',
  }
}

This needs two listeners to be set. One to handle the success "onload event" and the other to handle a fail "onerror".


let xhr = new XMLHttpRequest(); 
xhr.onload = function() {
    console.log(xhr.response);
};
xhr.onerror = function(err) {
    console.log('Problem: ' + err);
};
xhr.open('get', url);
xhr.send();


This example reads an external file

function xhrSuccess() { 
    this.callback.apply(this, this.arguments);
}

function xhrError() {
    console.error(this.statusText);
}

function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
    var xhr = new XMLHttpRequest();
    xhr.callback = callback;
    xhr.arguments = Array.prototype.slice.call(arguments, 2);
    xhr.onload = xhrSuccess; // specifies the callback function
    xhr.onerror = xhrError; // specifies a callback function
    xhr.open("GET", url, true);
    xhr.send(null);
}



export function callApi(url: string, requestInit?: RequestInit): Promise<string> { 
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.onload = function () {
      resolve(xhr.responseText);
    };

    xhr.onerror = function () {
      const error = {
        status: xhr.status,
        statusText: xhr.statusText,
        responseText: xhr.responseText,
      };
      reject(error);
    };

    const method = requestInit?.method ?? "GET";
    const headers = requestInit?.headers as Record<string, string> | undefined;
    const body = requestInit?.body as string | undefined;

    xhr.open(method, url, true);

    if (headers) {
      for (const header of Object.keys(headers)) {
        const val = headers[header];
        xhr.setRequestHeader(header, val);
      }
    }

    xhr.send(body);
  });
}



© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext