Categories
JavaScript Development

Get content from an API endpoint

XMLHttpRequest()

Until recently a request for data from an API endpoint would typically boil down to this:

let url = '/some/content.json',
	request = new XMLHttpRequest();

request.open('GET', url);
request.responseType = 'json';
request.send();

request.onload = function() {
	console.log(request.response);
}

request.onerror = function () {
	console.log("An error occurred.");
};

It’s not too much code and can handle most requests with little change, but it’s never been very easy for me to remember.


fetch()

Now we have fetch() though, which in my opinion has a much nicer syntax:

const url = '/some/content.json';

fetch(url, {
	'Method': 'GET',
	'Content-Type': 'text/json'
})
.then((response) => {
	return response.json();
})
.then((json) => {
	console.log(json);
})
.catch((error) => {
	console.log("An error occurred.");
});

Leave a Reply

Your email address will not be published. Required fields are marked *