To Lecture Notes

IT 231 -- Mar 5, 2024

Review Exercises

  1. This Elements Example displays information about the first eight elements in the periodic table. The URL
    localhost:3000/elements
    
    renders the views/index.ejs view, which displays a table with columns symbol, name, atomic number, and atomic mass for each of the first eight elements. When the Show link at the end of each row is clicked, it takes the user to the detail view views/show.ejs for that element. In addition to showing the information on the index view, an image is displayed showing the protons, neutrons, and electrons in an atom of that element. Here are the images to display on the show view:
         1.png  2.png  3.png  4.png  5.png  6.png  7.png  8.png

    The source code files for this example are shown below. However, these files contain errors, about eight errors per file, except for elements.json, that only contains three errors. Fix the errors, place the files in an Express project named Elements, then test the project. Fixing one of the pairs ( ), [ ], { } only counts as one error.
    --- Data file: data/elements.json ------------
    [{"symbol":"H","name":"Hydrogen",
           "atomicNumber":"1","atomicMass":"1.008"},
      {"symbol":"He","name":"Helium",
           "atomicNumber":"2","atomicMass":"4.003"},
      {"symbol":"Li","name":"Lithium",
           "atomicNumber":"3","atomicMass":"7.000"},
      {"symbol":"Be","name":"Beryllium",
           "atomicNumber":"4","atomicMass":"9.012"}
      {"symbol":"B","name":"Boron",
           "atomicNumber":"5","atomicMass":"10.810"},
      {"symbol":"C","name":"Carbon",
           "atomicNumber";"6","atomicMass":"12.011"},
      {"symbol":"N","name":"Nitrogen",
           "atomicNumber":"7","atomicMass":"14.007"},
      {"symbol":"O","name":"Oxygen",
           "atomicNumber":"8","atomicMass":"15.999"})
    --------------------------------------------
    // Source code file: main.js
    const express = require("express");
    const fs = require("fs");
    const app = express[ ];
    
    var data;
    fs.readFile("data/elements.json", (err, data) => {
        if(err) {
            console.log("Error reading elements.json file.");
        }
        else {
            console.log("Success reading elements.json file.");
            var elements = JSON.stringify(data);
        }
    });
    
    app.set("view engine", "ejs");
    app.use(express.static("public"));
    app.get("/elements", (req, res) -> {
        res.render("index", { elements: elements });
    );
    
    app.get("/elements/show/:aNum", (res, req) => {
        var aNum = parseInt(req.params.aNum);
        if (1 <= aNum && aNum <= 8) {
            res.showPage("show.ejs", 
                { aNum: aNum, elements: elements});
        }
        else {
            res.write("Array index out of range.");
        }
    });
    
    app.listen(3500, ( ) => {
        console.log("Server started.");
    });
    --------------------------------------------
    <DOCTYPE html>
    <!-- Source code file: views/index.ejs 
    
    <html lang="en">
        <head>
            <meta charset="unicode">
            <title>Elements -- Index View</title>
            <link rel="stylesheet" href="/public/css/styles.css">
        </head>
        <body>
            <h1>Elements -- Index View</h1>
            <table>
                <tr> 
                    <th>&nbsp;<br>Symbol</th>
                    <th>&nbsp;<br>Name</th>
                    <th>Atomic<br>Number</th>
                    <th>Atomic<br>Mass</th>
                    <th>&nbsp;</th>
                </tr>
                <%= for(let e of elements) { 
                    <tr>
                        <td><%= e.symbol %></td>
                        <td><% e.name %></td>
                        <td><%= e.atomicNumber %></td>
                        <td><%= e.atomicMass %></td>
                        <td><a href="/elements/show/:
                            <%= e.atomicNumber %>">
                        Show</a></td>
                    </tr>
               <% } %>
            </table>
        </body>
    </html>
    --------------------------------------------
    <!DOCTYPE html>
    <!-- Source code file: show.ejs -->
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Show<title>
            <link ref="stylesheet" href="/css/styles.css">
        </head>
        <body>
            <h1>Show -- Show View</h2>
            <% var element = elements[aNum - 1] %> 
            <p>Element Symbol: <%= element.symbol %></br>
               Element Name: <%= element.name %><br>
               Atomic Number: <%= element/atomicNumber %><br>
               Atomic Mass: <%= element.atomicMass %></p>
            <p>Image:<p>
            <img src="/public/images<% element.atomicNumber %>.png">
        </body>
    </html>
    --------------------------------------------
    /* Elements Example
       Source code file: public/css/styles.css */
    
    body { font: %100, verdana sans-serif; 
           background-color; #e0ffe0; 
           color: #004000; }
    table { border-collapse: collapse; }
    td { border: 004000 solid 2px; 
    td, th { padding= 5px; }
    img { width: 100in; }
    --------------------------------------------
    
    Answer: Here is the error log in case you want
    to practice fixing the errors and testing the project:
    
    // Source code file: data/elements.json
    1. Line 8: add a comma at the end of the line.
    2. Line 12: change the ; between "atomicNumber" and "6" to :.
    3. Line 16: at the very end of the line, change ) to ].
    // Source code file: main.js
    1. Line 4: change the [ ] at the end of line ( ).
    2. Line 6: change var data; to var elements;.
    3. Line 13: change from
       var elements = JSON.stringify(data);
       to
       elements = JSON.parse(data);
    4. Line 19: change -> to =>.
    5. Line 26: change
       res.showPage("show.ejs",
       to
       res.render("show",
    6. Line 30: change res.write to res.send.
    7. Line 34: replace the port number 3500
       with 3000. This is not really mistake, but
       it is a good idea to be consistant with port
       numbers.
    
    // Source code file: views/index.ejs.
    1. Line 1: replace DOCTYPE with !DOCTYPE.
    2. Line 2: add --> to the end of the line.
    3. Line 6: change charset="unicode" to charset="UTF-8".
    4. Line 20: replace <%= with <%.
    5. Line 24: replace <% with <%=.
    6. Line 27: remove the : at the end of the line.
    
    // Source code file: index.ejs.
    1. Line 6: Replace <title>Show<title> with
               <title>Show</title> 
    2. Line 7: Replace ref with rel.
    3. Line 10: Replace </h2> with </h1>.
    4. Line 12: Replace </br> with <br>.
    5. Line 17: Replace 
                /public/images<%
                with
                /images<%=
    
    // Source code file /public/css/styles.css.
    1. Line 4: replace 
               font: %100, verdana sans-serif; 
               by
               font: 100% verdana, sans-serif; 
    2. Line 8: replace 004000 with #004000.
    3. Line 9: replace padding= with padding;
    4. Line 10: replace 100in by 100px.
    

Practice Quiz 8a

Tutorial 5

Project 3

Practice Problems

  1. Write an Express app that inputs student information on a form like this:



    When this form is submitted, a view displaying the information received by the server is shown, for example:

  2. InputElements Example: Test these other values of the HTML input element type="text":
    text  number  password  date  range  color
    
    Use an alert box to display the the value of each input element after user input and button click. Here is the source code for testing an input element with type="text":
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Test Input Element</title>
            <script>
            function showValue( ) {
                var input1 = document.getElementById("in1");
                var value1 = input1.value;
                alert(`Value of input element: ${value1}`);
            }
            </script>
         </head>
         <body>
              <h2>Test Input Element</h2>
              <input type="text" id="in1"><br><br>
              <button onclick="showValue( );">
                  Show Value of Input Element
              </button>
        </body>
    </html>
    
  3. Rewrite Problem 1 as an Express app which does not use a server-side script. Display the output in the Node console instead of in an alert box.
  4. Start with this array of object literals:
    var pets = 
    {
        ID1001: { name: 'Sadie', animalType: 'dog', age: 3 },
        ID1009: { name: 'Coco', animalType: 'cat', age: 4 },
        ID1013: { name: 'Slinkie', animalType: 'snake', age: 2 },
        ID1016: { name: 'Thumper', animalType: 'rabbit', age: 2 },
        ID1027: { name: 'Max', animalType: 'dog', age: 5 },
        ID1029: { name: 'Duke', animalType: 'dog', age: 7 },
    };
    
    How can you determine if an object contains a specified key, for example ID1016?
  5. Write a for loop that computes the average age of the dogs.
  6. Look at the TestEjs5 Example. Modify it so that the form uses method="post". Here is are the modified source code files. Test them. Here are the source code files:
    -------------------------------------------------
    // Display a name obtained from an input form with
    // method=GET
    // Source code file: main.js
    const express = require("express");
    const app = express( );
    app.use(express.urlencoded({extended: false}));
    app.set("view engine", "ejs");
    
    app.get("/contact_info", (q, r) => {
        r.render("contact-info");
    });
    app.post("/contact_receipt", (q, r) => {
        console.log(q.body);
    r.render("contact-receipt", q.body);
    });
    app.listen(3000, ( ) => {
        console.log("Listening on port 3000.");
    });
    -------------------------------------------------
    // Source code file:
    <!DOCTYPE html>
    <!-- Source code file: contact-info.ejs -->
    
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>TestEjs2 Example</title>
        </head>
        <body>
            <h2>TestEjs5 Example</h2>
            <form name="form1" 
                  action="/contact_receipt" 
                  method="post">
                <label for="fname">First Name:</label><br>
                <input type="text" name="fname"><br><br>
                <label for="lname">Last Name:</label><br>
                <input type="text" name="lname"><br><br>
                <label for="phone">Phone:</label><br>
                <input type="text" name="phone"><br><br>
                <label for="email">Email:</label><br>
                <input type="text" name="email"><br><br>
                <input type="submit" value="Submit Contact Info">
            </form>
        </body>
    </html>
    -------------------------------------------------
    // Source code file:
    <!DOCTYPE html>
    <!-- Source code file: contact-receipt.ejs -->
    
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>TestEjs5 Example</title>
        </head>
        <body>
            <h1>TestEjs5 Example</h1>
    
            <p>Your contact information has been received<br>
               Thank you for your information.</p>
    
            <table>
                <tr> 
                    <th>First Name</th> <th>Last Name</th>
                    <th>Phone</th> <th>Email</th> 
                </tr>
                <tr>
                    <td><%= fname %></td> <td><%= lname %></td>
                    <td><%= phone %></td> <td><%= email %></td>
                </tr>
            </table>
        </body>
    </html>
    ------------------------------------------------