VAN
DEL
.IO

XMLHttpRequest request with setRequestHeader

This article is just a reference to future me or maybe you (Hello stranger!) on how to setup a XMLHttpRequest with a setRequestHeader and an EventListener for readystatechange in vanilla js.

No need for ajax or any other libraries.

Usage:
makeCorsRequest(‘https://api.pexels.com/v 1/search?query=people&per_page=1&page=1’)

 

Example api source retrieves an image from pexels.com
Requires setRequestHeader Authorization: MY_APIKEY , in createCORSRequest()

 



function createCORSRequest(method, url) {
	var xhr = new XMLHttpRequest();
	if ("withCredentials" in xhr) {
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
      xhr.setRequestHeader("Authorization", "MY_APIKEY");
	} else if (typeof XDomainRequest != "undefined") {
      // XDomainRequest for IE.
      xhr = new XDomainRequest();
      xhr.open(method, url);
      xhr.setRequestHeader("Authorization", "MY_APIKEY");
	} else {
      // CORS not supported.
      xhr = null;
	}
	return xhr;
}



function makeCorsRequest(url) {
	// This api requires an authentication header
	if (url) {
	var xhr = createCORSRequest('GET', url);
	if (!xhr) {
		alert('CORS not supported');
		return;
	}
	// Response handlers.
	xhr.onload = function() {
		var text = xhr.responseText;
		alert(xhr.responseText);
	};

	xhr.onerror = function() {
		alert('error making the request.');
	};
	xhr.send(); 
	}
}


//Follow the progress of the request with callback
function followRequestProgress(xhr, callback){
			
	xhr.addEventListener('readystatechange', function(e) {
		if(xhr.readyState == 2 && xhr.status == 200) {
			// Download is being started
			console.log('started');
		}
		else if(xhr.readyState == 3) {
			// Download is under progress
			console.log('ongoing');
		}
		else if(xhr.readyState == 4) {
			// Downloading has finished
			console.log('done callback ');
			
			// request.response holds the binary data of the font
			console.log(xhr.response);
			
			window[callback]();
			
		}
	});

}
	
//Usage

makeCorsRequest('https://api.pexels.com/v1/search?query=people&per_page=1&page=1')