To Lecture Notes

IT 231 -- Feb 22, 2024

Review Exercises

  1. What are some ways that we have used object literals in our Node and Express projects?
    Answer: We have obtained arrays of object literals from JSON data files using the JSON.parse method. We have also passed an object literal to define local variables in an EJS page, for example:
    res.render("index", { name: "Alice" });
    
    We also used an object literal to define the content type for a Node project:
    res.writeHead({"Content-Type", "text/html"});
    
  2. Which method do you use to convert an object literal into a JSON string? Answer:
    JSON.stingify
    
  3. Which method do you use to convert a JSON string into an object literal? Answer:
    JSON.parse
    
  4. Puzzle Problem: what is the output?
    const s = `[{"x":5,"y":1},{"x":3,"y":2},{"x":0,"y":4},
                {"x":1,"y":3},{"x":-1,"y":1}]`;
    const a = JSON.parse(s);
    var sum = 0;
    for(let i = 0; i <= 3; i++) {
        sum += a[i].x * a[i+1].y;
    }
    console.log(sum);
    // Answer:
    // Variable Trace Table:
      i    sum  product a[i].x a[i+1].y
    =====+=====+=======+======+========
            0
      0    10     10     5        2
      1    22     12     3        4
      2    22      0     0        3
      3    23      1     1        1
    Output: 23
    
  5. Change the Magic8Ball Example so that it reads the array of predictions from the file predictions.json in the data folder.
    Answer: create a folder for an Express project named magic-8ball, initialize the project and install express and ejs:
    > npm init
    > npm i express ejs
    
    Create data and views folders with files predictions.json, main.js, magic-8ball.ejs, and route-not-found.ejs using this structure:
    -- Folder and file structure for Magic8Ball Example.
    data
        predictions.json
    views
        magic-8ball.ejs
        route-not-found.ejs
    main.js
    
    Here are the source code files:
    -----------------------------------
    // Magic8Ball Example
    // Source code file: main.js
    
    const express = require("express");
    const fs = require("fs");
    const app = express( );
    const PORT = 3000;
    
    // Set View Engine to EJS
    app.set("view engine", "ejs");
    
    // Array of 20 Magic 8-Ball Predictions
    var preds; 
    fs.readFile("data/predictions.json", (err, data) => {
       if (err) {
           console.log("Error reading from predictions.json");
       }
       else {
           preds = JSON.parse(data);
       }
    });
    
    // Define /prediction route.
    app.get("/prediction", (req, res) => {
        // Pass the preds array to the EJS page.
        res.render("magic-8ball.ejs", { predictions: preds});
    });
    
    // If undefined route is entered, show route-not-found 
    // page.
    app.get("*", (req, res) => {
        res.render("route-not-found.ejs");
    });
    
    // Start server for port 3000.
    app.listen(PORT, ( ) => {
        console.log(`Server listening on Port ${PORT}`);
    });
    -----------------------------------
    <!DOCTYPE html>
    
    <!-- Magic8Ball Example 
         Source code file: views/magic-8ball.ejs -->
    
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Magic 8-Ball Prediction</title>
        </head>
        <body>
            <!-- Choose Random Prediction -->
            <% var n = predictions.length;
            var randomIndex = 
                Math.floor(Math.random( ) * n);
            var prediction = predictions[randomIndex]; %>
    
            <h1>Magic 8-Ball Prediction</h1>
    
            <!-- Display random prediction on EJS page. -->
            <p><%= prediction %></p>
        </body>
    </html>
    -----------------------------------
    <!DOCTYPE html>
    
    <!-- Magic8Ball Prediction
         Source code file: views/route-not-found.ejs -->
    
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Route Not Found</title>
        </head>
        <body>
            <h1>Route Not Found</h1>
            <p>Please check the route and try again.</p>
        </body>
    </html>
    -----------------------------------
    
  6. Change the DisplaySite3 Example so that it reads the specials data from the file specials.json in the data folder. Answer:
    create a folder for an Express project named magic-8ball, initialize the project and install express and ejs:
    > npm init
    > npm i express ejs
    
    Create data and views folders with files specials.json, main.js, specials.ejs, and route-not-found.ejs using this structure:
    -- Folder and file structure for Specials Example.
    data
        specials.json
    views
        specials.ejs
        route-not-found.ejs
    public
        css
            styles.css
    main.js
    
    Here are the source code files:
    -----------------------------------
    const express = require("express");
    const fs = require("fs");
    const app = express( );
    
    // Define specialsArray as a global variable (outside 
    // of any function to it can be used anywhere in the 
    // script.
    var specialsArray;
    
    fs.readFile("data/specials.json", (err, data) => {
        if (err) {
            console.log("Error reading from specials.json.");
        }
        else {
            specialsArray = JSON.parse(data);
        }
    });
    
    // Set up the static folder named public
    app.use(express.static("public"));
    
    // Set up method call to handle the 
    // /specials route.
    app.get("/specials", (req, res) => {
       res.render("specials.ejs", 
                  {specials: specialsArray});
    });
    
    // Start the server.
    app.listen(3000, ( ) => {
        console.log("Server started.");
    });
    -----------------------------------
    <!DOCTYPE html>
    <!-- DisplaySite3 Example
         Source code file: views/specials.ejs -->
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Specials Example</title>
            <link rel="stylesheet" href="/css/styles.css">
        </head>
        <body>
            <h1>Specials Example</h1>
            <table>
            <% for(s of specials) { %>
                <tr> 
                    <td><%= s.city %></td>
                    <td><%= s.length %></td>
                    <td>$<%= s.price %></td>
               </tr>
            <% } %>
            </table>
        </body>
    </html>
    -----------------------------------
    /* DisplaySite3 Example
       Source code file: public/css/styles.css */
    
    body { font-family: arial; }
    table { border-collapse: collapse; }
    td { border-style: solid; border-width: 2px; }
    td, th { padding: 5px; }
    -----------------------------------
    

Practice Quiz 6b

Obtaining Input from a URL Parameter

UrlParameter Example:

Obtaining Input from a GET Query

GetQuery Example: