09 - Fetch From One
In this module, we'll create and access the /one
endpoint and do a GET
request to access data for display in the DOM.
Server Addition
When writing applications, it's common to have to toggle between the front-end and back-end. With that being said, let's add another route in the testcontroller.js
file. This can be anywhere in the file, but we'll put it just before module.exports = router
.
Analysis
Notice that we find the
attributes
for two of the columns:id
&testdata
. This is part of sequelize. If you are querying an entire table, you can choose which columns you want to grab from. The other columns will not be queried, which can save time for a giant table.
Be sure to save the changes to your server.
Overview
Let's go back to the client and into the 01-scripts.js
file. Right below the postData
method, let's write another method. This time we'll pull in the data and think through the starter logic of showing it in the DOM. Here is the code to be added:
Summary
Let's break this down:
We set up our URL in one variable and target the
data-one
id in the DOM in another one.We create a
fetch()
withHeaders
and therequest method ofGET
. There are also chained promises that handle the data when it returns or handle an error if one comes back.Inside the final
.then()
, we are going to work towards showing the returned data in the DOM. We start by targeting thegetjson
id in the DOM and attaching the value to themyList
variable.We set up a
for of
loop.We write a
console.log()
statement to show how we can access the values that come back in the object inside the response.We create another variable called
listItem
. ThecreateElement()
method will create that type of element in the DOM. In this case, we create a list item,li
, every time we iterate.Each time we iterate, we store the value of
r.testdata
in the newly createli
.We call
appendChild
onmyList
, which means that each time we iterate we put theli
into the unordered list.
Quick Summary for the DOM Work
Just to succinctly summarize the last then()
:
We target a list,
myList
.We iterate over the response object with a
for of
loop.Each time we iterate, we create a list item.
The value gets stored in the
innerHTML
of theli
.We append the list item to an unordered list.
We continue until we get to the end of the response object.
Test
Make sure that both your client and server are running.
Go to
localhost:8080
Click the
Display Data
button in Step #5.You should see the following success message:
Last updated