Fetch API & JSON¶
1. JSON (JavaScript Object Notation)¶
JSON is a format for storing and transporting data.
Parse (String to Object)¶
let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
const obj = JSON.parse(text);
Stringify (Object to String)¶
2. Fetch API¶
The Fetch API interface allows web browser to make HTTP requests to web servers. It uses Promises.
Basic GET Request¶
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log('Request Failed', err));
Async/Await Syntax (Cleaner)¶
async function getTodo() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There was a problem:', error);
}
}
Industry Standard
Before fetch, developers used XMLHttpRequest. fetch is much cleaner and is now the standard for network requests in modern browsers.