Javascript Fetch API

Sending a Request

let response = fetch(url);
fetch(url)     
.then(response => {
// handle the response
})
.catch(error => {
// handle the error
});

Reading the Response

fetch('/readme.txt')     
.then(response => response.text())
.then(data => console.log(data));
async function fetchText() {     
let response = await fetch('/readme.txt');
let data = await response.text();
console.log(data); }

Handling the status codes of the Response

async function fetchText() {     
let response = await fetch('/readme.txt');
console.log(response.status); // 200
console.log(response.statusText); // OK

if (response.status === 200) {
let data = await response.text();
// handle data
}
}
fetchText();
200 
OK
let response = await fetch('/non-existence.txt');  
console.log(response.status); // 400
console.log(response.statusText); // OK
400
Not Found

JavaScript Fetch API example

[{         
"username": "john",
"firstName": "John",
"lastName": "Doe",
"gender": "Male",
"profileURL": "img/male.png",
"email": "john.doe@example.com"
},
{
"username": "jane",
"firstName": "Jane",
"lastName": "Doe",
"gender": "Female",
"profileURL": "img/female.png",
"email": "jane.doe@example.com"
}
]
<!DOCTYPE html> 
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API Demo</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container"></div>
<script src="js/app.js"></script>
</body>
</html>
async function getUsers() {
let url = 'users.json';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
async function renderUsers() {
let users = await getUsers();
let html = '';
users.forEach(user => {
let htmlSegment = `<div class="user">
<img src="${user.profileURL}" >
<h2>${user.firstName} ${user.lastName}</h2>
<div class="email"><a href="email:${user.email}">${user.email}</a></div>
</div>`;

html += htmlSegment;
});
let container = document.querySelector('.container');
container.innerHTML = html;
}
renderUsers();

In Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store