HAKATEMIA
27JavaScript basics

JavaScript Fetch and XHR

Easy25MIN

Fetch and XHR are two ways to send network requests in JavaScript. Fetch is a newer API that has been available since 2015 and it provides a more modern and simpler way to send network requests. XHR (XMLHttpRequest) is an older way to send network requests and it has been in use since 2005.

Fetch

The Fetch uses the Promise interface, which enables easy management of asynchronous operations. The use of Fetch is simple, as it contains only one function that returns a Promise object. With this function, network requests can be sent and responses can be handled. For example:

JAVASCRIPT
1fetch('https://jsonplaceholder.typicode.com/posts')
2  .then(response => response.json())
3  .then(data => console.log(data))
4  .catch(error => console.error(error));
1 / 4
Hakatemia Pro

Learn to hack — start here

Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.