To Lecture Notes

IT 231 -- Feb 1, 2024

Review Exercises

  1. Write a Node script to display the numbers from 1 to 999 in a localhost browser, 10 numbers per line. Answer:
    const http = require("http");
    const app = http.createServer( (req, res) => {
        res.writeHead(200, {ContentType: "text/html"});
        res.write("<h1>1 to 1000 Example</h1>");
        res.write("<p>");
        for(let n = 1; n <= 1000; n++) {
            res.write(n + " ");
            if (n % 10 == 0) {
                res.write("<br>");
            }
        }
        res.write("<p>");
        res.end( );
    });
    app.listen(3000);
    console.log("Server listening on Port 3000");
    
  2. What is a JavaScript object literal?
    Answer: It is a list of key-value pairs separated by commas and delimited by curly braces ( { } ). For example:
    var person = { name: 'Alice', gender: 'F', age: 11 }; 
    
    A JavaScript object literal is like a Python dictionary, except that the keys don't need quotes.
  3. Start with this object literal:
    var groceryItem = { item: "Green Peas", price: 0.98 };
    
    a. Print the price of the item:
    console.log(groceryItem.price);
    
    b. Add this new key-value pair: quantity: 15.
    groceryItem.quantity = 15;
    
  4. Starting with this array arr of object literals:
    var arr = [ {a: "123", b: "234"}, {a: "567", b: "890"} ];
    convert arr to a JSON string, then convert the JSON string back to the array object literals arr2. Answer:
    var s = JSON.stringify(arr);
    console.log(s);
    // Output:
    [{"a":"123",b":"234"},{"a":"567","b":"890"}];
    var arr2 = JSON.parse(s);
    // Output:
    [ 
        {a: "123", b: "234"}, 
        {a: "567", b: "890"}
    ]

Practice Quiz 4b

HTTP

HTTP Request-response Cycle

Practice Problems

  1. As we have seen, HTTP is a network protocol for requesting and sending pages over the World Wide Web. The most common HTTP methods (also called verbs) are GET (requests the server to send back a specified resource) and POST (sends data back to the server). Try out this Node script:
    const PORT = 3000;
    const http = require("http");
    const app = http.createServer((req, res) => {
        res.write(`<p>${req.method}<br>`;
        res.write(`${req.url}</p>`);
        res.end( );
        console.log(req.headers);
    });
    app.listen(PORT);
    
    Predict the output. Browser output:

    GET
    /

    // Object literal output to the Node console:
    {
        host: 'localhost:3000', 
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) 
            Gecko/20100101 Firefox/109.0',
        accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,
            image/avif,image/webp,*/*;q=0.8',
        'accept-language': 'en-US,en;q=0.5',
        'accept-encoding': 'gzip, deflate, br',
        dnt: '1',
        connection: 'keep-alive',
        'upgrade-insecure-requests': '1',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'none',
        'sec-fetch-user': '?1'
    }
    
  2. DisplaySite1 Example: Write a Node script that displays hardcoded webpages, depending on the URL that is entered.
    --------------------------------
    URL: localhost:3000/
    Displayed webpage:
    <html>
        <head>
            <title>Homepage</title>
        </head>
        <body>
            <h1>Acme Travel Homepage</h1>
            <p>Welcome to Acme Travel Agency</p>
        </body>
    </html>
    --------------------------------
    URL: localhost:3000/contact_us
    Displayed webpage:
    <html>
        <head>
            <title>Contact Us</title>
        </head>
        <body>
            <h1>Contact Acme Travel</h1>
            <p>Phone Numbers:<br>
               Main: 312/234-5678<br>
               Fax:  312/234-5679</p>
        </body>
    </html>
    --------------------------------
    URL: localhost:3000/specials
    Displayed webpage:
    <html>
        <head>
            <title>Specials</title>
        </head>
        <body>
            <h1>Acme Travel Specials</h1>
            <table>
                <tr> 
                    <th>City</th> 
                    <th>Tour Length</th>
                    <th>Price</th>
                </tr>
                <tr>
                    <td>Barcelona</td> 
                    <td>5 days</td>
                    <td>$2095</td>
                </tr>
                <tr>
                    <td>London</td> 
                    <td>9 days</td>
                    <td>$3545</td>
                </tr>
                <tr>
                    <td>Paris</td> 
                    <td>13 days</td>
                    <td>$9965</td>
                </tr>
            </table>
        </body>
    </html>
    --------------------------------
    URL: any other URL other than the three above.
    Displayed webpage:
    <html>
        <head>
            <title>Route not Found</title>
        </head>
        <body>
            <h1>404: Page not Found</h1>
            <p>Sorry, we couldn't find that page.</p>
        </body>
    </html>
    
    Write this HTTP header information for each webpage:
    res.writeHead(200, {"Content-Type": "text/html" }); 
    
    1. Write Node script that checks the URL using if..else statements and displays the corresponding webpage. Answer:
      const PORT = 3000;
      const http = require("http");
      const app = http.createServer((req, res) => {
          res.writeHead(200, {"Content-Type": "text/html" });
          var url = req.url;
          if (url == "/") {
              res.write(`
              <html>
                  <head>
                      <title>Homepage</title>
                  </head>
                  <body>
                      <h1>Acme Travel Homepage</h1>
                      <p>Welcome to Acme Travel Agency</p>
                  </body>
             </html>
             `);
          }
          else if(url == "/contact_us") {
              res.write(`
              <html>
                  <head>
                      <title>Contact Us</title>
                  </head>
              <body>
                  <h1>Contact Acme Travel</h1>
                  <p>Phone Numbers:<br>
                  Main: 312/234-5678<br>
                  Fax: 312/234-5679</p>
                  </body>
              </html>
              `);
          }
          else if(url == "/specials") {
              res.write(`
              <html>
                  <head>
                      <title>Specials</title>
                  </head>
                  <body>
                      <h1>Acme Travel Specials</h1>
                      <table>
                          <tr> 
                              <th>City</th> 
                              <th>Tour Length</th>
                              <th>Price</th>
                          </tr>
                          <tr>
                              <td>Barcelona</td> 
                              <td>5 days</td>
                              <td>$2095</td>
                          </tr>
                          <tr>
                              <td>London</td> 
                              <td>9 days</td>
                              <td>$3545</td>
                          </tr>
                          <tr>
                              <td>Paris</td> 
                              <td>13 days</td>
                              <td>$9965</td>
                          </tr>
                      </table>
                  </body>
              </html>
              `);
          }
          else {
              res.write(`
              <html>
                  <head>
                      <title>Route not Found</title>
                  </head>
                  <body>
                      <h1>404: Page not Found</h1>
                      <p>Sorry, we couldn't find that page.</p>
                  </body>
              </html>
              `);
          }
          res.end( );
      });
      app.listen(PORT);
      
    2. Instead of using if..else statements like you did in Part a, use a switch statement to select the correct webpage for each URL. Answer:
      const PORT = 3000;
      const http = require("http");
      const app = http.createServer((req, res) => {
          res.writeHead(200, {"Content-Type": "text/html" });
          switch(req.url) {
              case "/":
                  res.write(`
                  <html>
                      <head>
                          <title>Homepage</title>
                      </head>
                      <body>
                          <h1>Acme Travel Homepage</h1>
                          <p>Welcome to Acme Travel Agency</p>
                      </body>
                  </html>
                  `);
                  break;
              case "/contact_us":
                  res.write(`
                  <html>
                      <head>
                          <title>Contact Us</title>
                      </head>
                      <body>
                          <h1>Contact Acme Travel</h1>
                          <p>Phone Numbers:<br>
                          Main: 312/234-5678<br>
                          Fax: 312/234-5679</p>
                     </body>
                 </html>
                 `);
                 break;
             case "/specials") {
         
                 res.write(`
                 <html>
                     <head>
                         <title>Specials</title>
                     </head>
                     <body>
                         <h1>Acme Travel Specials</h1>
                         <table>
                             <tr> 
                                 <th>City</th> 
                                 <th>Tour Length</th>
                                 <th>Price</th>
                             </tr>
                             <tr>
                                 <td>Barcelona</td> 
                                 <td>5 days</td>
                                 <td>$2095</td>
                             </tr>
                             <tr>
                                 <td>London</td> 
                                 <td>9 days</td>
                                 <td>$3545</td>
                             </tr>
                             <tr>
                                 <td>Paris</td> 
                                 <td>13 days</td>
                                 <td>$9965</td>
                             </tr>
                         </table>
                     </body>
                 </html>
                 `);
                 break;
             default:
                 res.write(`
                 <html>
                     <head>
                         <title>Route not Found</title>
                     </head>
                     <body>
                         <h1>404: Page not Found</h1>
                         <p>Sorry, we couldn't find that page.</p>
                     </body>
                 </html>
                 `);
          }
          res.end( );
      });
      app.listen(PORT);
      
  3. DisplaySite2 Example. Store the data for specials webpage of the DisplaySite1 Example in a JSON string. Then rewrite this example reading the page information from this string. Use JSON.parse first to convert the JSON string to an array of object literals. Use this specials HTML page for the /specials route:
    --------------------------------
    URL: localhost:3000/specials
    Displayed webpage:
    <html>
        <head>
            <title>Specials</title>
        </head>
        <body>
            <h1>Acme Travel Specials</h1>
            <table>
                <tr> 
                    <th>City</th> 
                    <th>Tour Length</th>
                    <th>Price</th>
                </tr>
                <tr>
                    <td>Barcelona</td> 
                    <td>5 days</td>
                    <td>$2095</td>
                </tr>
                <tr>
                    <td>London</td> 
                    <td>9 days</td>
                    <td>$3545</td>
                </tr>
                <tr>
                    <td>Paris</td> 
                    <td>13 days</td>
                    <td>$9965</td>
                </tr>
            </table>
        </body>
    </html>
    --------------------------------
    
    Answer:
    const PORT = 3500;
    const http = require("http");
    const app = http.createServer((req, res) => {
    
    // Set up and use JSON file for specials data.
    var data = `[{"city":"Barcelona","length":5,"price":2095},
                 {"city":"London","length":9,"price":3545},
                 {"city":"Paris","length":13,"price":2095}]`;
    var specials = JSON.parse(data);
    
    if (req.url == "/specials") {
        res.writeHead(200, {"Content-Type":"text/html"});
        res.write(`
    <html>
        <head>
            <title>Specials</title>
            <style>
            body { font: 100% helvetica, arial, sans-serif; 
                   background-color: #b0b0ff; } 
            h1 { color: navy; }
            p { color: #404040; }
            table { border-collapse: collapse; }
            td { border: 2px black solid; }
            td, th { padding: 5px; }
            </style>
        </head>
        <body>
            <h1>Acme Travel Specials</h1>
            <table> 
                <tr> 
                    <th>City</th> 
                    <th>Tour Length</th>
                    <th>Price</th>
                </tr>
       `);
        for(let s of specials) {
            res.write("<tr>\n");
            res.write(`<td>${s.city}</td>`);
            res.write(`<td>${s.length}</td>`);
            res.write(`<td>$${s.price}</td>`);
            res.write("</tr>\n");
        }
        res.write(`
            </table>
        </body>
    </html> 
                 `);
        }
        else {
            res.writeHead(200, {"Content-Type":"text/html"});
            res.write("<p>Route not Found</p>");
        }
        res.end( );
    });
    app.listen(PORT);
    

Midterm Review Guide

The File System Module fs

Reference: W3Schools Node.js File System Module
www.w3schools.com/nodejs/nodejs_filesystem.asp

Reading from Files