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
  • Overview
  • Server Addition
  • 01-scripts.js
  • Analysis
  • Test
  • CORS
  1. js_library
  2. Node Server
  3. 09 - Middleware

02 - Test Client JS

In this module, we're going to start adding the JavaScript functions that will enable us to make client-side requests to our server.

Overview

So far, we've been using Postman to test all of our endpoints. Postman is great, but we want to see how to get the data and start showing it in the DOM. Again, we're just keeping the DOM stuff in a simple Bootstrap table for now, and we're going to be focused solely on getting data into the DOM. We can worry about prettying things up another day.

Server Addition

Just for reorientation, let's add something a little extra in our server:

  1. Go to your testcontroller.js file in the controllers folder.

  2. Add the following route:

    /************************
    * GET:  Get simple message from server
    ***********************/
    router.get('/helloclient', function (req, res) {
    res.send('This is a message from the server to the client.')
    })
  3. Go ahead and save the code.

01-scripts.js

Now, let's move over to the client side and do the following: 1. Go into the 01-scripts.js file. 2. Add the following code:

function fetchHelloDataFromAPI() {
    fetch('http://localhost:3000/test/helloclient', { //1
        method: 'GET', 
        headers: new Headers({ //2
          'Content-Type': 'application/json'
        })
    })
        .then(function (response) {
            console.log("Fetch response:", response)
            return response.text(); //3
        })
        .then(function (text) {
            console.log(text);
        });
}
  1. Open the index.html file and take a look at where the function gets called:

Analysis

  1. Test endpoint with fixed value to verify server works.

  2. Send our headers to the server with the Headers() constructor object. We'll talk more about this in a later module.

  3. The value received is a string, not a JSON object, so .text() is used instead of .json()

Test

Let's test it by doing the following:

  1. In your console window in VS Code, click the + sign to open a new console window. You can switch between windows using the dropdown next to the +. You can also right-click a folder in the File Explorer and select Open in Command Prompt(Windows) or Open in Terminal (Mac) to open a console window in that specific folder.

  2. Navigate to your server folder and start the server side using nodemon app.js.

  3. NOTE: If you client is already running, skip this step. Open another new terminal window, navigate to the client folder, and start the client side using http-server -o. This will start the client and automatically open a new tab in your browser at 127.0.0.1:8080 (same as localhost:8080).

  4. Click any of the buttons on screen. You should see an error:

CORS

When a client and server are both running at the same time, they run on different ports. By default, a server won't recognize any transmission coming from a different URL than its own, and it will refuse to acknowledge the request. This is known as a CORS error, which stands for Cross Origin Resource Sharing. We can fix errors like this with files known as middleware, which we'll talk more about in the next chapter.

Previous01 - Test Client HTMLNext03 - Middleware intro

Last updated 7 years ago

screenshot
screenshot