CodeBlanks Logo Icon CodeBlanks

Summary - Fetch API

JavaScript course · Intermediate · Lesson 89/134

Build a client function that makes GET and POST requests with fetch and handles errors.

Fetch API summary

In this group you learned to send a request to a server with fetch, read the response and the body, add headers, send data with POST, and handle HTTP errors.

const response = await fetch(url, {
  method: 'POST',
  body: 'hello',
  headers: { 'Content-Type': 'text/plain' }
});
if (!response.ok) {
  throw new Error('HTTP ' + response.status);
}
const body = await response.text();

You can now combine all these steps in a single client function: make the request, check for errors, read the body, and return the result. Two short tasks will help you practice this.

Exercise Write a getData function

Write an async function named getData that takes a url parameter. Inside it, put the response into a response variable with await fetch(url). If !response.ok, throw with throw new Error('HTTP ' + response.status). Then put the body into a body variable with await response.text() and return it with return body.

Show example solution
async function getData(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('HTTP ' + response.status);
  }
  const body = await response.text();
  return body;
}

Exercise Write a postData function

Write an async function named postData that takes url and body parameters. Inside it, put the response into a response variable with await fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'text/plain' } }). Then return response.status with return.

Show example solution
async function postData(url, body) {
  const response = await fetch(url, {
    method: 'POST',
    body: body,
    headers: { 'Content-Type': 'text/plain' }
  });
  return response.status;
}

Test yourself

  1. In a GET request, how do you read the body?

    const response = await fetch(url);
    • You read it with await response.text()
    • You read it directly with response.body
    • You read it with response.headers.get('body')
    • You read it with response.status
    Show answer

    You read it with await response.text() — Correct! You read the body with await response.text().

  2. Match the fetch pieces

    fetch(url, options)
    Sends the request
    await response.text()
    Reads the body
    if (!response.ok)
    Checks for errors
  3. Add an error check

    const response = await fetch(url);
    if (____) {
      throw new Error('HTTP ' + response.status);
    }
    Show answer
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('HTTP ' + response.status);
    }

All lessons in Intermediate