Forbes magazine logo Ranked Best Coding Bootcamps 2023

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

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #89

Enroll for May 6th, 2024