arrow-left

All pages
gitbookPowered by GitBook
1 of 2

Loading...

Loading...

real-world-fetch

index

Learn how to handle errors and submit data with the fetch method

The browser's fetch method is deliberately low-level. This means there are certain things you'll almost always need to do to make requests in a real application.

hashtag
HTTP errors

fetch is only concerned with making HTTP requests. From this perspective as long as it receives a response it was successful, even if that response says something like 500 server error. Most of the time in your application code you want to treat non-200 status codes as errors.

hashtag
Challenge

  1. Open workshop.html in your editor

  2. Add a fetch call to "https://echo.oliverjam.workers.dev/status/404" (this always returns a 404)

We need to handle HTTP responses we don't want. We can do this by checking the response.ok property. This will be true for successful status codes (like 200) and false for unsuccessful ones (like 404 or 502).

hashtag
Challenge

  1. Edit your .then() to check the response's ok property

  2. If the response is not okay throw a new error with the status property of the response

hashtag
Submitting data

fetch allows us to make any kind of HTTP request we like. So far we have made GET requests, but those won't allow us to submit data to a server. To do that we'll need to configure some options by passing a second argument to fetch. E.g.

This can include lots of properties. Here are some useful ones:

  • method: to use methods other than GET

  • headers: to send extra info about the request. e.g. if we're submitting JSON we should set the "content-type" header to "application/json"

hashtag
Challenge

  1. Edit your fetch to send a POST request to "https://echo.oliverjam.workers.dev/json"

  2. Send a JSON body containing an object with whatever properties you like

hashtag
User input

So far we've only hard-coded our requests. In reality they're usually triggered by a user submitting a form or clicking a button. There are several different ways we can access form data in our JavaScript.

hashtag
Forms

Forms are the semantically correct element for receiving user input. We should use them even when we're using JS to handle the request (rather than relying on the native browser submission).

We can add a handler for the submit event like this:

event.preventDefault() will stop the browser trying to send the request for you. We want to handle the request with fetch instead.

In order to send our request we have to get hold of the values the user entered. There are a few ways we could do this.

hashtag
Challenge: querySelector

We can use to directly access each input element, then get its value. For example document.querySelector("#username").value.

  1. Create a form with two inputs and a submit button

  2. Add a "submit" event handler to the form (don't forget preventDefault)

  3. Use querySelector

hashtag
Challenge: new FormData()

There is a built-in API that mirrors a form's native behaviour. We can use new FormData(myForm) to create a . This is what the form would send if we didn't call preventDefault(), and contains all the input values.

If we want to submit this as JSON we need to turn it into a normal object. You can do this with . Note: fromEntries() is relatively new and isn't supported in older browsers.

hashtag
Challenge

  1. Edit your previous solution

  2. Use new FormData() to get all the input values

  3. Turn the FormData into an object to submit

hashtag
Workshop

We're going to make a Pokémon search page using the .

  1. Create a form with a search input and submit button

  2. When the form is submitted request the Pokémon the user typed from "https://pokeapi.co/api/v2/pokemon/NAME"

  3. If the request succeeds show the Pokémon's name and sprite

hashtag
Stretch goals

If you have extra time try using some of the other data in the response body to show e.g. the pokémon's types or stats. Write some CSS to make it pretty!

Solution preview

Add a .then() and .catch(). Which of these runs? What does the response look like?
Now does your .catch() run?

body: to send information to the server. If we're sending JSON we also need to JSON.stringify the data.

Don't forget the "content-type"!
to get each input's value
  • Use fetch to POST the data as JSON to the same URL as before

  • Log the response you get from the server

  • If the request fails show a relevant error to the user

    options objectarrow-up-right
    querySelectorarrow-up-right
    FormData interfacearrow-up-right
    Object.fromEntries(data)arrow-up-right
    PokéAPIarrow-up-right
    fetch("example.com", {
      method: "POST",
    });
    const myForm = document.querySelector("form");
    
    myForm.addEventListener("submit", event => {
      event.preventDefault();
      // handle the submission yourself here
    }))