Fetching from front-end to back-end using API.

Josh burger
3 min readJun 4, 2021

Hello, Today I would like to go over how fetches work and how I learned to use them for my Javascript project. The requirements for my project were to make 3 AJAX fetches. The first AJAX fetch I made was to retrieve all games in my API back-end.

For this fetch, I put it inside of a function fetch games() within this function I have a variable that grabs my games container by the id. After I call the fetch to my back end inside of the () after fetch. It then makes a call to my backend looking at my routes.

After it finds the route I'm looking for and the correct controller, Inside of that controller it will look inside the index route which looks like this because I fetched for all games.

Inside of this route, it looks at the index route with games = Game.all and then renders JSON: games. After all of that is completed I get back a promise that looks like this.

We then have to take the response given back and call .json() which will return a promise object that we can use to create our JavaScript objects (games).

Then the data is received and I iterate over the data using .forEach game create a new game with the data we got back. Finally, I use the const g and call the function addToDom to render the games on the HTML.

A little more about using fetch: The fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

When I say asynchronously I mean a given program’s code will run straight along, with only one thing happening at once. If a function relies on the result of another function, it has to wait for the other function to finish and return, and until that happens.

I really enjoyed using fetch during my project because it allowed me to really understand what's going on between front-end and back-end and how to reach into the back end to grab the data I want to work with and display.

--

--