To Lecture Notes

IT 231 -- Feb 8, 2024

Review Exercises

  1. For the callback function passed in to app.createServer, what is the difference between the request and response objects?
    Answer: the request object is concerned with the requests that are received from the user, for example the URL or the HTTP command (GET or POST). The response object handles the output that is displayed in the browser. The methods are writeHead (writes information to the HTTP head, write (writes content to the browser body), end (flushes the output buffer to the browser body).
  2. Explain what these operators are:
    **  ++  +=  .  [ ]
    
    Answer:
    ** -- exponentiation, e.g., 2 ** 3 == 8
    ++ -- increment, which means add one to the variable, e.g., n++
    += -- assignment operator, which can mean either addition for numbers or concatenation for strings.
            For example, if n has the value 3, then after n += 2; n will have the value 5.
            If s has the value "abc", then after s += "xyz"; s will have the value "abcxyz".
  3. Write JavaScript statements that will rewrite an array such as
    [23, 54, 33, 16, 9]
    
    to this
    23,54,33,16,9
    
    Answer, Complicated Solution:
    function compress(a) {
        var output = "";
        for(var item of a) {
            output += item + ",";
        }
        // Use slice method to eliminate
        // the training comma.
        return output.slice(0, -1);
    }
    // Use the compress method.
    var arr = [23, 54, 33, 16, 9];
    var s = compress(arr);
    console.log(s);
    
    Answer, Simple Solution:
    var s = arr.toString( );
    console.log(s);
    
  4. Fix the errors in the code with errors at the end of Tutorial 3.
    Answers: Check the class video to see what the corrections were.
  5. Write a Node script that reads the route from the browser, then displays this route in the browser window and in the Node console. Answer:
    const http = require("http");
    const app = http.createServer((req, res) => {
        res.writeHead(200, {"Content-Type": "text/html"});
        var route = req.url;
        res.write(`<p>URL: ${route}</p>`);
        res.end( );
        console.log("URL: " + route);
    });
    app.listen(3000);
    
  6. Start with this a1 object literal:
    const a1 = { 
                 name:  "Alice",
                 phone: "222/333-4444",
                 email: "alidell@gmail.com" 
              };
    
    Write a statement that outputs the phone number of Alice to the Node console. Also display her email in address in the localhost browser. Answer:
    // Method 1
    console.log(a1.phone);
    // Method 2
    console.log(a1['phone']);
    // Display in localhost browser:
    // Include code for a1 object literal here.
    const http = require("http");
    const app = http.createServer( (q, r) => {
        r.writeHead(200, {'Content-Type':'text/html'});
        r.write(a1.name);
        r.end( );
    });
    app.listen(3000);
    
  7. Instead of starting with the object literal a1, start with this JSON string:
    var s = '{"name":"Alice","phone":"222/333-4444",
              "email","alidell@depaul.edu"}';
    
    Answer:
    var a1 = JSON.parse(s);
    res.write(`<p>Phone: ${a1.phone}</p>`);
    console.log(a1.email);
    
  8. Change the preceding exercise to read the JSON string s from the input file data/student.json. Answer:
    // main.js script
    const http = require("http");
    const fs = require("fs");
    const app = http.createServer( (req, res) => {
        res.writeHead(200, {"Content-Type": "text/html"});
        fs.readFile("data/student.json", (err, data) => {
            var a1 = JSON.parse(data);
            res.write(`<p>${a1.phone}</p>`);
            res.end( );
            console.log(a1.email);
        });
    });
    app.listen(3000);
    // --------------------------------------------
    // data/student.js data file
    {"name":"Alice","phone":"222/333-4444",
    "email":"alidell@depaul.edu"}
    

Introduction to Express.js

Request Object Properties

  1. Create a new Express project or use an existing one.
  2. Use this source code for the main.js script:
    // Define PORT constant and assign the
    // express application to the constant app.
    const express = require("express"),
          app = express( );
    
    // Set up a GET route for the homepage.
    app.get("*", (req, res) => {
        res.send(`<p>URL: ${req.url}</p>`);
        console.log(req.query);
    });
    
    // Set server to listen on port 3000
    const PORT = 3000;
    app.listen(PORT, ( ) => {
        console.log("Server started; " +
            `listening on port ${PORT}.`);
    });
    
    Try out this example with these URLs:
    localhost:3000/contact_us
    localhost:3000/contact_us/phone
    localhost:3000/new_contact?fname=Alice&lname=Lidell
    

Routes using Express

CommonJS Modules