Created
March 4, 2021 19:03
-
-
Save prof3ssorSt3v3/9a72917262433be5bf819d8d9a46d3f7 to your computer and use it in GitHub Desktop.
Code from the video about why fetch headers matter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Request Headers</title> | |
<style> | |
html { | |
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, | |
Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; | |
background-color: #222; | |
font-size: 20px; | |
line-height: 1.6; | |
} | |
h1 { | |
color: orangered; | |
} | |
h2 { | |
color: orange; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>How to Read Headers</h1> | |
<h2>From an HTTP Response</h2> | |
<script> | |
let url = 'http://127.0.0.1:5500/237-400x300.jpg'; | |
let options = { | |
method: 'GET', | |
}; | |
fetch(url, options) | |
.then(async (resp) => { | |
if (!resp.ok) throw resp.statusText; | |
console.log({ resp }); | |
console.log(resp.headers.get('content-type')); | |
//append() delete() get() has() | |
//values() keys() entries() set() | |
for (let h of resp.headers) { | |
// console.log(h); | |
} | |
let type = resp.headers.get('content-type'); | |
let obj = { | |
html: null, | |
json: null, | |
blob: null, | |
}; | |
if (type.startsWith('text/html')) { | |
obj.html = await resp.text(); | |
} else if (type.startsWith('application/json')) { | |
obj.json = await resp.json(); | |
} else if (type.startsWith('image/')) { | |
obj.blob = await resp.blob(); | |
} | |
return obj; | |
}) | |
.then(({ html, json, blob }) => { | |
//handle the contents of the file | |
if (html) { | |
const doc = new DOMParser().parseFromString(html, 'text/html'); | |
// console.log(doc.body); | |
let h1 = doc.querySelector('h1'); | |
console.log(h1.textContent); | |
} | |
if (json) { | |
//js object | |
} | |
if (blob) { | |
//image | |
let img = document.createElement('img'); | |
let url = URL.createObjectURL(blob); | |
img.src = url; | |
document.body.append(img); | |
} | |
}) | |
.catch((err) => { | |
console.warn(err.message); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment