JS-301-NodeServer
  • Introduction
  • js_library
    • Node Server
      • 00 - Intro
        • 01 - Purpose
        • 02 - Back-End Setup
        • 03 - Terms Cheat Sheet
      • 01 - Server Set up
        • 01 - npm packages
        • 02 - Express Intro
        • 03 - Express code
      • 02 - Development Tools
        • 01 - Nodemon Intro
        • 02 - Postman Intro
        • 03 - Postman set up
      • 03 - Routes Intro
        • 01 - Routes intro
        • 02 - Express Router() intro
        • 03 - Challenge 1
        • 04 - Challenge 2
      • 04 - Database Intro
        • 00 - DB Intro and Set up
          • 00 - DB Intro
          • 01 - PostgreSQL Intro
          • 02 - Install
        • 01 - Sequelize Intro
          • 01 - Sequelize intro
          • 02 - Initialize
      • 05 - Model View Controller
        • 01 - MVC
          • 00 - MVC Intro
        • 02 - Models
          • 01 - Intro to Models
          • 02 - Test Model
        • 03 - Controllers
          • 00 - Controllers Intro
          • 01 - Controller Set up
          • 02 - Create Method
          • 03 - req.body()
          • 04 - Crafting the Response
          • 05 - Sending the Response
          • 06 - JSON Response
          • 07 - Error Handling
        • 04 - Conclusion
      • 06 - Tokenization
        • 01 - JWT Intro
          • 01 - JWT intro
        • 02 - User Create
          • 01 - User Create
          • 02 - Refactor
        • 03 - User Token
          • 01 - JWT Package
          • 02 - Adding JWT
          • 03 - ENV
      • 07 - Encryption
        • 01 - bcrypt
        • 02 - bcrypt setup
      • 08 - Session
        • 00 - Session Intro
        • 01 - Sign In Method
        • 02 - Sign In Bcrypt
        • 03 - Sign In JWT
      • 09 - Middleware
        • 01 - Test Client HTML
        • 02 - Test Client JS
        • 03 - Middleware intro
        • 04 - Headers intro
        • 05 - Server Update
        • 06 - Test Post
        • 07 - Test Post Refactor
        • 08 - Post Data
        • 09 - Fetch From One
      • 10 - Authenticated Routes
        • 01 - Intro to Authenticated Routes
        • 02 - Validate Session
        • 03 - Changes to app.js
        • 04 - authtestcontroller.js
        • 05 - Delete an Item
        • 06 - Update an Item
        • 07 - Postman Testing
      • 11 - Authenticated Requests
        • 00 - Additions to index
        • 01 - Anatomy of a Request
        • 02 - Create User
        • 03 - Getting a Token
        • 04 - Get Items From One User
        • 05 - Creating an Item for a User
        • 06 - Get one item
        • 07 - Update an Item
        • 08 - Deleting an Item
        • 09 - Deleting with a Custom Event
      • 12 - Workout Log Server
        • 00 - Intro
      • 13 - More Sequelize Functions
        • Migrations
          • 00 - Intro
          • 01 - init and config
          • 02 - Creating the First Migration
          • 03 - Running Migrations
          • 04 - Reverting Migrations
          • 05 - Seeds
          • 06 - Reverting Seeds
        • Queries
          • 00 - Intro
          • 01 - Queries
Powered by GitBook
On this page
  • Server Addition
  • Analysis
  • Overview
  • Summary
  • Quick Summary for the DOM Work
  • Test
  1. js_library
  2. Node Server
  3. 09 - Middleware

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.

/************************
 * GET:  /one
 ***********************/
router.get('/one', function(req, res) {

  TestModel
    .findAll({ //1
        attributes: ['id', 'testdata']
    })
    .then(
        function findAllSuccess(data) {
            console.log("Controller data:", data);
            res.json(data);
        },
        function findAllError(err) {
            res.send(500, err.message);
        }
    );
});

Analysis

  1. 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:

/***************************************
 * 4 GET FROM /ONE - Display Data
*************************************/
function fetchFromOneDisplayData(){
    //1
    let url = 'http://localhost:3000/test/one';
    let dataView = document.getElementById('display-one');   

    //2
    fetch(url, {
      method: 'GET', 
      headers: new Headers({
        'Content-Type': 'application/json'
      })
    }).then(
        function(response){
            return response.json()
        })
    .catch(
        function(error){
            console.error('Error:', error)
        })
    .then(
        function(results){
            let myList = document.querySelector('#getjson'); //3

            for (r of results){  //4
                console.log('Response:', r.testdata); //5
                var listItem = document.createElement('li');  //6 
                listItem.innerHTML = r.testdata; //7
                myList.appendChild(listItem); //8
            }
        })
}

Summary

Let's break this down:

  1. We set up our URL in one variable and target the data-one id in the DOM in another one.

  2. We create a fetch() with Headersand therequest method of GET. There are also chained promises that handle the data when it returns or handle an error if one comes back.

  3. Inside the final .then(), we are going to work towards showing the returned data in the DOM. We start by targeting the getjson id in the DOM and attaching the value to the myList variable.

  4. We set up a for of loop.

  5. We write a console.log() statement to show how we can access the values that come back in the object inside the response.

  6. We create another variable called listItem. The createElement() method will create that type of element in the DOM. In this case, we create a list item, li, every time we iterate.

  7. Each time we iterate, we store the value of r.testdata in the newly create li.

  8. We call appendChild on myList, which means that each time we iterate we put the li 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 the li.

  • We append the list item to an unordered list.

  • We continue until we get to the end of the response object.

Test

  1. Make sure that both your client and server are running.

  2. Go to localhost:8080

  3. Click the Display Data button in Step #5.

  4. You should see the following success message:

Previous08 - Post DataNext10 - Authenticated Routes

Last updated 7 years ago

screenshot