• Brooke Bachman

Fetch Requests and Post Requests from an API in Javascript

When I was first learning about fetch requests, the new syntax was quite confusing to me.I was used to Ruby on Rails, where we had forms and routes, and used these to retrieve data from our tables and databases.

We are working in Javascript, why does it look like a hash rocket from Ruby?

In line 2, another way to represent this data is here:

Here is a form I created on my frontend in Javascript.

Notice how I typed in all of my attributes in their boxes. These are the attributes all of my clothing items need to have.

When someone clicks my "Add Clothes" button, this will trigger my event listener.

This event listener will tell my frontend to make a fetch request to my backend.

Here is a post request where I add a clothing item to my clothing API.

In line 173, I am fetching data from this link that gives me all of the clothing items. The "/clothings" is a route I actually created on my backend with rails.

This route is for my index page. This is where all of the clothing items will render on my server.

I created my own API, so I am using a rails server for my backend.

In line 174, I am doing more than just fetching data. That is why I need to specify which method I am doing, in this case it is "POST".

It is a post request because I am filling out a form with the attributes that my clothing class requires.

In line 175 I have my headers, these specify what type of data I want to get back from our API.

In line 179 I am telling the API what data I need. I am also changing the data to a string with JSON.stringify.

Once I receive the data in JSON format. I am creating the clothing object.

In lines 180-186, the keys for the clothing object are its attributes. This allows me to use the data I am getting back from the fetch in the exact format I am looking for.

The values from these keys are the actual values that the person typed into my form, that I showed above.

The event.target is the form when someone clicks on it. My event listener is keeping track of the events. More on this later.

The values for the keys are the inputs from the form I created in order to create a clothing item.

The 'POST' method on the frontend communicates with my create method on my Rails backend.

In line 189 I am returning the backend response in json format. You have to use the return keyword in Javascript because there is not a implicit return.

In line 191 I am console logging my clothingData, which is an object. If you are not totally sure what you are receiving back from your fetch, using console log to see what it looks like in the chrome, console is very useful.