Skip to content

Apr 08: Review Weeks 7–10

Learning Objectives

After today's class, you should be able to:

  • Summarize the types of questions that will be asked on the exam.
  • Write JavaScript on paper to fetch APIs and manipulate the DOM.
  • Identify areas that you need to review and study before Thursday.

Lesson Outline

Debrief [15 min]

  • Solutions for Preps 7–9 and Labs 6–8
  • Exam 2 learning objectives / resources

Review [35 min]

  • Answer the following sample questions
  • Practice writing your solutions on paper
Question 1

Consider the following variables for a "to-do list" app:

  • The HTML page contains an <ol> element with the ID "todoList".
  • allTodos is an array of strings representing the user's to-do items.

Write JavaScript code that selects the <ol> element, removes any existing children, and adds a list item for each string in allTodos. (You don't need to write this code within a function; allTodos is global.)

Question 2

The Rhyming and Word Information API has an endpoint at:

const url = 'https://rhymebrain.com/talk?function=getRhymes&word=';

When this API endpoint receives a GET request, it sends a json response that contains an array of objects representing words that rhyme with the word parameter. For example, the response for word=ace is:

[
    {"word":"case","freq":27,"score":300,"flags":"bc","syllables":"1"},
    {"word":"face","freq":26,"score":300,"flags":"bc","syllables":"1"},
    {"word":"base","freq":24,"score":300,"flags":"bc","syllables":"1"},
    // many more...
]

Write a function named rhymeIt that takes a parameter named query and does the following:

  1. Make a request to the API with the value of query (at the end of url).
  2. When the response becomes available, correctly process the json data.
  3. For each object in the data, log the object's word property in the console.
  4. If an error occurs at any point, show the details using console.error().
Question 3

In the previous question, the rhymeIt function can be written in two ways:

  1. As a series of chained function calls: fetch(), then(), and catch().
  2. As an async function that uses await to handle asynchronous calls.

Additionally, logging each word in the results can be done in two ways:

  1. Using a loop (Ex: for, for...in, for...of).
  2. Using the forEach() array method.

Rewrite your solution for Question 2 using a different combination of these approaches. For example, if your solution used 1 and 4, rewrite your code using 2 and 3.

Project [25 min]

  • Set up a mock API for testing
  • Deploy with ssh and rsync
    • Linux/macOS: these commands are built-in
    • Windows: use the Git Bash shell in VS Code

The following command copies (recursively) the src/ folder to stu, replacing existing contents under www/project/.

rsync -av --delete src/ stu:www/cs343/project/
Note: I will put this command in a file named deploy.sh in your project repo. You can run ./deploy.sh to automate your deployment on the stu server.

Mock API Example

mock_api.js

/**
 * Check if the app is running in the live server.
 *
 * @returns {boolean} true if running on localhost
 */
function isLocalhost() {
  return ['localhost', '127.0.0.1'].includes(window.location.hostname);
}

/**
 * Convert a remote URL to a local path for testing.
 * Example: "https://reqres.in/api/users" -> 'reqres.in/api/users.json'
 *
 * @param {string} url resource to fetch from an API
 * @returns {string} path to json file on localhost
 */
function jsonifyURL(url) {
  const loc = new URL(url);
  return `${loc.hostname}${loc.pathname}.json`;
}

/**
 * Wrapper for the fetch function that uses local files for testing.
 * If an error occurs when running in production (not on localhost),
 * this function will fetch the local test files as a backup plan.
 *
 * @param {*} url resource to fetch from an API
 * @param {*} options object with custom settings
 * @returns Promise that resolves to a Response object
 */
function mockFetch(url, options) {
  if (isLocalhost()) {
    return fetch(jsonifyURL(url), options);
  } else {
    return fetch(url, options)
      .catch((err) => {
        console.error(err);
        return fetch(jsonifyURL(url), options);
      });
  }
}

SSH Configuration

SSH, which stands for Secure Shell, is a network protocol that enables remote login. In the CS department, we have an SSH server named stu (which is short for student). The stu server allows you to access CS department resources from off campus.

For convenience, you can set up configuration files for SSH. Go to the hidden folder named .ssh in your home directory. If the folder doesn't exist, you should create the folder. Follow the instructions below to edit (or create) the following files.

The config file

Open (or create) the file named config in your .ssh folder. Paste the contents below into the file. If you already have an entry for Host stu, then copy only the lines you don't have. Replace username with your JMU username (the one you log into Canvas with).

Host stu
Hostname stu.cs.jmu.edu
User username  # CHANGE TO YOUR E-ID!!
ServerAliveInterval 60
ServerAliveCountMax 5

This configuration does the following:

  • A host named "stu" is defined. That way, you can simply type ssh stu instead of ssh username@stu.cs.jmu.edu on the command line.
  • The SSH connection will be kept alive by sending a packet every 60 seconds. If this fails 5 times, the connection will be considered closed.

The known_hosts file

Open (or create) the file named known_hosts in your .ssh folder. Paste the contents below into the file. If you already have an entry for stu.cs.jmu.edu, then copy only the parts you don't have.

stu.cs.jmu.edu,134.126.141.221 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPcm1mzS2xJyjaMZXtEN0JvFw7bbLyPjPLwXj6AJm2Y9/c06Y4bNnT3AaK/Xnl013fOPmcgDFirAZ+jdMK11lZM=

This line defines the "public key" of the stu server, so that when you connect, you can be sure it's really the stu server and not a hacker posing as the stu server. Establishing identity is important, given that passwords and other sensitive information might be sent over the connection.

id_rsa and id_rsa.pub

By default, the stu server will ask you for your JMU password (the one you log into Canvas with). However, you can avoid having to type your password by creating a public/private key pair. If you don't already have id_rsa and id_rsa.pub files, run the following command to create them:

ssh-keygen

Press enter to accept the default options. When prompted, enter a passphrase that you can remember. The passphrase will be used to "unlock" your private key. Without a passphrase, someone could steal your id_rsa file and log in as you.

authorized_keys

After the ssk-keygen command finishes, run the following command to authorize your key on the stu server:

ssh-copy-id stu

If that command does not work, do the following:

  1. Copy the contents of your id_rsa.pub file to the clipboard.
    • You will paste this line during Step 3 below.
  2. ssh stu
    • Log in with your JMU password.
  3. cd .ssh
    • If the directory does not exist, mkdir .ssh
    • Then cd .ssh so you are in that directory.
  4. echo PASTE_HERE >> authorized_keys
    • Replace PASTE_HERE with your key from Step 1.
  5. logout

At this point, you should be able to type ssh stu on the command line to connect to the stu server without having to enter your JMU password.