Fetch: Getting the body content

A response has a body, accessible using several methods:

  • text() returns the body as a string
  • json() returns the body as a JSON-parsed object
  • blob() returns the body as a Blob object
  • formData() returns the body as a FormData object
  • arrayBuffer() returns the body as an ArrayBuffer object

All those methods return a promise. Examples:

fetch('./file.json')
  .then(response => response.text())
  .then(body => console.log(body))
fetch('./file.json')
  .then(response => response.json())
  .then(body => console.log(body))

Get JSON

The same can be written using async functions

;(async () => {
  const response = await fetch('./file.json')
  const data = await response.json()
  console.log(data)
})()

Lessons in this unit:

0: Introduction
1: How to use Fetch
2: Catching errors in network requests
3: The Response object
4: ▶︎ Getting the body content
5: The Request object
6: Request headers
7: POST requests
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!