LogoLogo
  • FAC Curriculum
  • archive
    • Node & npm introduction
    • developer
      • Programming Paradigms
    • handbook
      • Asking for help
      • Coaching groups
      • Code review
      • Course rules
      • Debugging
      • Employment schedule and material delivered in FAC20
      • GitHub Workflow
      • Glossary or terms
      • Presentation Guidance
      • Equality, Diversity and Inclusion
      • Installation guide
      • Learning circles
      • Mentoring guidance
      • What to expect from your mentors
      • One-day projects
      • Pair programming
      • Portfolio
      • Questions for problem solving
      • Progress Logs
      • Final project report
      • Managing software projects
      • Project Presentations
      • Project roles
      • Projects
      • Retrospectives
      • Role Circles
      • Safeguarding policy
      • Technical Spikes
      • System requirements
      • Tech for Better
      • User Manuals
      • Wellbeing Support
      • project-docs
        • What makes a mentor?
        • Product Handover
        • Sprint Planning
        • Tech for Better Presentations
        • User Research & Usability Testing
    • foundation
      • full-stack
        • Learning Outcomes
        • project
      • testing
        • project
        • spikes
  • docs
    • Contributing to the curriculum
    • Curriculum intent
    • Curriculum process
  • src
    • About our curriculum
    • course
      • Code of Conduct
      • Docker
      • .NET and Umbraco
      • Getting started
      • Founders and Coders coursebook
      • KSB's
      • Mini projects
      • Revision checklist
      • Svelte
      • TypeScript
      • handbook
        • Software Developer Handbook
        • Software Foundation Handbook
      • precourse
        • Before you start the course
        • Installation List
      • syllabus
        • developer
          • app
            • learning-outcomes
            • project
            • schedule
            • spikes
          • introduction
            • learning-outcomes
            • project
            • resources
            • schedule
          • week00-pre-course
            • We'd like you to spend some time before starting the course working on useful fundamentals.
            • spikes
          • week01-project01-basics
            • Employability introduction
            • Homework
            • learning-outcomes
            • Week of September 9th
            • project
            • resources
            • schedule
            • spikes
          • week02-project02-chatbot
            • employability
            • Homework
            • learning-outcomes
            • Week of September 16th
            • project
            • resources
            • schedule
            • spikes
          • week03-project03-server
            • Learning Outcomes
            • Week of September 23th
            • The Amazin' Quizzer API Backend
            • resources
            • schedule
          • week04-project03-frontend
            • learning-outcomes
            • Week of September 30th
            • UI for Quizzer App
            • resources
            • schedule
          • week05-project03-test-deploy
            • Testing and deployment
            • Week of October 7th
            • project
            • resources
            • schedule
          • week06-project04-databases
            • learning-outcomes
            • Week of October 14th
            • project
            • Databases
            • schedule
          • week07-project04-authentication
            • Learning Outcomes
            • Week of October 21st
            • project
            • resources
            • schedule
          • week08-project04-test-deploy
            • Learning Outcomes
            • Week of October 28th
            • project
            • resources
            • schedule
          • week09-reading-week
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
          • week10-project05-DOTNET-intro
            • Learning Outcomes
            • overview
            • project
            • Resources
            • schedule
          • week11-project05-DOTNET-testing
            • Testing and deployment
            • Week of November 18th
            • project
            • Resources
            • schedule
          • week12-project05-DOTNET-deploy
            • Learning Outcomes
            • Week of November 25th
            • project
            • Resources
            • schedule
            • Spikes
          • week13-TFB-design
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
            • Design Week Spikes
          • week14-TFB-build
            • Learning Outcomes
            • overview
            • Project
            • DevOps Resources
            • schedule
            • Spikes
          • week15-TFB-build
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
            • Spikes
          • projects
            • in-house-design
              • Learning Outcomes
              • Project
              • Resources
              • schedule
              • Design Week Spikes
        • foundation
          • Obsolete-full-stack
            • project
          • post-course
            • Homework
            • schedule
        • portfolio
          • fruit-shop
            • learning-outcomes
            • project
            • resources
          • game
            • learning-outcomes
            • project
            • resources
          • hobby-page
            • learning-outcomes
            • project
            • resources
          • movie-data
            • learning-outcomes
            • project
            • resources
          • project-gallery
            • learning-outcomes
            • project
            • resources
          • website
            • learning-outcomes
            • project
            • JavaScript
        • tfb
          • week 1
            • Introduction (45 minutes)
            • Further reading
          • week 10
            • content
            • resources
          • week 11
            • What will we be doing this week?
            • resources
          • week 12
            • What will we be doing this week?
            • Further reading
          • week 2
            • Discover (90 minutes)
            • resources
          • week 3
            • content
            • resources
          • week 4
            • Mapping the user journey (90 minutes)
            • resources
          • week 5
            • Figma Workshop 1 (90 minutes)
            • Further reading
          • week 6
            • Figma Workshop 2 (90 minutes)
            • resources
          • week 7
            • Product pitches & Selection (90 minutes)
            • resources
          • week 8
            • content
            • resources
          • week 9
            • content
            • resources
    • learn
      • DOTNET
        • Introduction to .NET
      • auth
        • Authenticating web apps
      • database
        • Persisting data with SQLite and Node
      • dotnet-two
        • Dependency injections and interfaces in .NET
      • form-validation
        • Form validation
      • react
        • Building client-side apps with React
      • server
        • HTTP servers with Node & Express
      • typescript
        • TypeScript
    • mentoring
      • design-week
        • Analysis Workshop
        • Code planning
        • Definition Workshop
        • Discovery Workshop
        • Figma introduction
        • Usability testing
        • User Research
    • resources
      • http
        • introduction
    • workshops
      • cookie-auth
        • index
      • creating-promises
        • index
      • css-layout
        • index
      • cypress-testing
        • index
      • database-testing
        • index
      • dev-tooling
        • Developer tooling
      • dom-challenge
        • index
      • dom-rendering
        • index
      • es-modules
        • index
      • express-middleware
        • Express middleware
      • first-class-functions
        • index
      • form-validation
        • index
      • functions-callbacks-async
        • Functions, callbacks, & async JavaScript
      • git-intro
        • Introduction to Git
      • git-terminal
        • Using Git in the terminal
      • git-workflow
        • Git workflow
      • github-projects
        • GitHub Projects Workflow Workshop
      • heroku-sql-challenge
        • index
      • html-forms
        • index
      • learn-a11y
        • index
        • starter-files
          • solution
            • Accessibility solution explanation
      • learn-fetch
        • index
      • learn-integration-testing
        • index
      • learn-testing
        • Learn testing in JavaScript
      • learn-unit-testing
        • index
      • node-error-handling
        • Node error-handling
      • node-express-server
        • Node and Express HTTP server
      • node-npm-intro
        • Node & npm introduction
      • node-postgres
        • Learn Postgres with Node
      • node-scripting-challenge
        • index
      • password-security
        • index
      • promise-practice
        • index
      • react-components
        • React components
      • react-fetch
        • index
      • react-forms
        • React forms
      • react-refactor-classes
        • index
      • react-state-effects
        • React state & effects
      • real-world-fetch
        • index
      • scope-challenge
        • Scope debugging challenge
      • semantic-html
        • index
      • server-side-forms
        • Server-side forms
      • session-auth
        • Session authentication
      • sql-intro
        • index
      • tdd-array-methods
        • index
Powered by GitBook
On this page
  • HTTP errors
  • Challenge
  • Challenge
  • Submitting data
  • Challenge
  • User input
  • Forms
  • Challenge: querySelector
  • Challenge: new FormData()
  • Workshop
  • Stretch goals
Export as PDF
  1. src
  2. workshops
  3. 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.

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.

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)

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

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).

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

  3. Now does your .catch() run?

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.

fetch("example.com", {
  method: "POST",
});
  • 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"

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

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

  3. Don't forget the "content-type"!

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.

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:

const myForm = document.querySelector("form");

myForm.addEventListener("submit", event => {
  event.preventDefault();
  // handle the submission yourself here
}))

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.

Challenge: querySelector

  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 to get each input's value

  4. Use fetch to POST the data as JSON to the same URL as before

  5. Log the response you get from the server

Challenge: new FormData()

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

Workshop

  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

  4. If the request fails show a relevant error to the user

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

Previousreal-world-fetchNextscope-challenge

Last updated 4 years ago

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

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

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.

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

options object
querySelector
FormData interface
Object.fromEntries(data)
PokéAPI