SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

How to use JavaScript fetch API

Altcademy Team wrote on 7 February 2018

The key in using fetch is that you need to handle request error yourself. You do it by checking the initial response.ok property. If the response replied with status in between 200 - 299, response.ok will be True, otherwise False.
fetch('api.com/resourse').then(function(response) { if(response.ok) { return response.json(); // Expecting JSON data } throw new Error('Network response was not ok.'); }).then(function(json) { console.log(json); }).catch(function(error) { console.log('There has been a problem with your fetch operation: ' + error.message); });
Calling fetch with just a URL will result in a default GET request. If you need to change your method or add headers, pass in an object as the second argument to fetch.
const options = { method: 'POST', credentials: 'include', mode: 'same-origin', headers: { Accept: 'application/json', // Add for sending JSON data 'Content-Type': 'application/json', // Add for sending JSON data 'X-CSRF-Token': 'AuthenticityToken', 'X-Requested-With': 'XMLHttpRequest', }, body: JSON.stringify({ foo: 'bar', }), } fetch('api.com/resourse', options).then(function(response) { if(response.ok) { return response.json(); // Expecting JSON data } throw new Error('Network response was not ok.'); })

Trusted by

Students and instructors from world-class organizations

Join the upcoming Cohort #111

Enroll for March 2nd, 2026