Final P2 Flashcards

1
Q

form tag itself has two very important attributes.

A
  1. Action which specifies where the form should be sent

2. Method which specifies the HTTP method to be used in the HTTP request sent when the form is submitted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

percent-encoding or URL encoding

A

certain special characters that have a specific meaning within URLs are encoded with other characters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

T or F: A GET request will send the same data as POST. But instead of sending it as part of the URL, it is sent in the body of the request.

A

False: A POST request will send the same data as GET. But instead of sending it as part of the URL, it is sent in the body of the request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

T or F: Unless we use the HTTPS protocol, which encrypts the HTTP communication, an intruder can see the body of a POST request.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

T or F: even when using HTTPS protocol, we must not use GET for submitting sensitive data, such as passwords. Many web servers log the URL of HTTP requests, and putting sensitive data in the URL with GET requests can result in that data being saved in log files.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

T or F: Another limitation of POST is that browsers often place a limitation on the length of the query string, whereas no such limits are placed on the body length.

A

False: GET

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Processing a submitted form in ___ requires adding a route for the URL and HTTP method specified in the form. ___ then provides the data submitted in the form as a JSON object to our route handler function

A

Express

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

GET route handler example

A

app.get(“/review”, (req, res) => {
console.log(req.query);
res.send(req.query);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

POST route handler example

A

app.post(“/review”, (req, res) => {
console.log(req.body);
res.send(req.body);
});

app.use(express.urlencoded({
extended: true
}));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

T or F: CSS is a language for describing the presentation of documents. It allows us to specify rules using which we can selectively style HTML elements. Typically we write these CSS rules into stylesheets which are files containing CSS rules.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

CSS selector

A

selects the HTML element to which the rule applies

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

CSS format

A

h1 {
color: red;
font-size: 25pt;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

CSS: The universal selector *

A

matches all elements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

CSS: The ___selector matches elements based on the element ___

A

type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

CSS: The ___ selector selects the single element with a matching __ and is of the form #id

A

ID

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

CSS: The ___ selector selects all elements in which the attribute class has that value

A

class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

T or F: IDs are good for anchoring and specifying unique blocks, whereas classes are more about design properties that get used again and again.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

CSS: Is it possible to specify rules that apply to multiple selectors.?

A

Yes, This is done by specifying multiple selectors separated by commas.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

CSS: We can specify selectors that select elements based on their location in the document

A

combinator selector

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

CSS: We can combine selectors to form more complex selectors. A common use is combining a type and a class to specify a selector that applies to tags with that type but only if they have that particular class. The syntax for this is tag.class.

A

Complex Selector

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

CSS also supports selectors that are based on the state of an element

A

CSS Pseudo Selectors

selector:pseudo-class {
property: value;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

T or F: Common use cases for CSS pseudo-classes are changing the style of an element when the mouse hovers over it, and displaying visited links differently from links that have not been visited.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

CSS: Rule Precedence

A
  1. Later rules overrule earlier rules.

2. Rules with a more specific selector take precedence over those with more general selectors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Colors in CSS are represented in three ways.

A
  1. Hex (hexadecimal) values in the form of #RRGGBB.
  2. Decimal values in the form of rbg(x, y, z)
  3. Named colors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

T or F: In CSS, the absolute units are not relative to anything, whereas the relative units are relative to something else, e.g., the size of the parent element.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

The most commonly used relative units are __ and __.

A
  1. em

2. rem

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

T or F: em is a relative unit based on the current font size of the parent element. For example, 2em means two times the parent element’s current font size.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

T or F: rem is a relative unit based on the current font size of the root element. For example, 2rem means two times the current font size of the root element.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Size Properties in the Box Model

A
  1. Element (width/height)
  2. Padding (padding-top, etc.)
  3. Margin (margin-top, etc.)
  4. Border (can specify color, style, width)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

T or F: The position CSS property sets how an element is positioned in a document. The top, right, bottom, and left properties determine the final location of positioned elements.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

T or F: With relative positioning, the browser figures out where something should to be positioned using its default positioning algorithm.

A

False: static

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

T or F: Elements with static positioning are moved in relation to where they would be placed by the static positioning.

A

False: relative

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

T or F: Elements with absolute positioning are positioned in relation to the parent element.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

T or F: Elements with fixed positioning are positioned with respect to the document window

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

T or F: As a first step to rendering a page, the browser parses the HTML document and creates a DOM tree from it. From there the browser renders the page by rendering each node of the DOM tree.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

T or F: The DOM (Document Object Model) is the model that a browser uses to render a web page

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

T or F: The DOM gives a representation of a document as a logical tree of nodes and includes an API for interacting with this tree representation. This allows us to write programs to statically access and modify the content, structure, and style of an HTML document.

A

False: This allows us to write programs to DYNAMICALLY access

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

T or F: Versions of DOM are referred to as levels. When we read the DOM specification on the W3C website we will find a description of interfaces rather than the description of the API in a particular programming language.

A

True: This is because the DOM specification is programming language neutral. Many programming languages have implemented the DOM specification so that programs written in that language can use the DOM API.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

T or F: The object ___ represents the browser window and the object ___ represents the webpage currently loaded in this browser window.

A
  1. window

2. document

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

T or F: The object document gives us an entry point into the DOM tree that the browser has built up after it parsed the webpage.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

DOM tree includes nodes of the following type:

A
  1. Document
  2. Document Type
  3. Element
  4. Attribute
  5. Text
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Any node that has one or more children has the following properties:

A
  1. firstElementChild
  2. lastElementChild
  3. nextElementSibling
  4. previousElementSibling
  5. children
  6. parentNode
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

T or F: All of these are methods for searching for elements:

  1. getElementById
  2. getElementsByTagName
  3. getElementsByClassName
  4. querySelector
A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

T or F: Probably the most basic property of a node is its textContent. This contains all the text content of a node, and its children, in a string representation.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

T or F: Setting a node’s textContent to an empty string will clear out all of its text and that of its child nodes.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Nodes of type element have a property named ___which get the HTML markup within an element.

A

innerHTML

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

As we can see ___ of this p element contains its text content and that of its child element b concatenated as a string, but it does not contain the HTML tags or the attribute. On the other hand, the ___ property contains all the HTML content, including the tags of child elements and attributes inside the element book.

A
  1. textContent

2. innerHTML

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

T or F: Using the property innerHTML to insert text into a webpage is a security risk. It is recommended that the insertion of plain text should be done using textContent and should not use innerHTML

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

Adding nodes in a DOM tree is a two step process:

A
  1. Create the node by calling the appropriate method on the document object.
  2. The newly created node does not yet appear in the DOM tree. As the second step, we insert the new node at the desired position in the DOM tree.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

T or F: The method document.createTextNode() can be used to create new text nodes. However, in most cases we can simply add text content using the textContent property we discussed earlier, rather than creating a text node.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

T or F: To create elements we use the method document.createElement().. It takes one argument which is the name of the element we want to create and returns an element of that type. However, the newly created element does not yet exist in the DOM tree.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

T or F: There are many different methods available to insert nodes in a DOM tree, but one of the most common ways to insert elements is calling the method appendChild(newChild) on a node. This method will add the node newChild as the last child of the node the method was called on.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

the method ___ and pass it the node we want to remove as an argument

A

removeChild()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

When a user takes an action, the browser dispatches an event based on the type of user action. We can use JavaScript to register functions called event handlers. What type of programming is this?

A

event-driven programming

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

T or F: When an event of particular type occurs, the browser executes the event handler registered for that type of event. We can program event handler functions so that they modify attributes of DOM nodes, modify the DOM tree or send HTTP requests to a webserver, thus providing interactivity in our application.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

Event handling requires specifying 3 things

A
  1. What happened, i.e., what is the event of interest?
  2. Where did this event occur, i.e., what is the element of interest?
  3. What to do, i.e., what JavaScript code to invoke when the event occurs on this element?
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Types of DOM events that should be handled

A
  1. mouse-related events
  2. keyboard-related events
  3. focus-related events
  4. form submission events
  5. Input event
  6. page related events
  7. timer events
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

There are two ways to register an event handler to execute when an event occurs on an element.

A
  1. Register the JavaScript code inline, as the value of an attribute with the name of the event (not recommended).
  2. Register the JavaScript code using the DOM API.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Registering an event handler on an element: Register the JavaScript code using the DOM API format

A

myElem.addEventListener(‘click’, mouseClick)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Example: Registering an Event Handler

A
// The browser can pass the event to the event handler
        function mouseClick(event) {
            console.log('Mouse clicked on the following element');
            // The property event.target is set to the element which dispatched
            // the event. We will discuss this and other properties of 
            // event in the next section.
            console.log(event.target);
            // If the color is currently red, set it to green.
            // Otherwise set it to red.
            event.target.style.color = event.target.style.color === 'red' ?
                            'green' : 'red';
        };
    window.onload = function () {
        document.getElementById('registerWithDOM').addEventListener("click", mouseClick);
    };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

T or F: We remove an event handler from an element by calling the method removeEventListener on this element.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Example: Removing an Event Handler

A
function unbindButton() {
            document.getElementById('backgroundChanger').removeEventListener('click', changeColor);
        }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

T or F: When an event is raised, the browser cannot pass an object corresponding to this event to our handler.

A

False, it can

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

Some of the most important properties of this object include the following:

A
  1. type: the name of the event, e.g., click, mouseup, etc.
  2. timeStamp: the time that the event was created.
  3. target: the element that dispatched the event.
  4. currentTarget: the element on which the event listener was registered.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

T or F: Load events are called when a resource and all of its dependent resources have finished loading. When we want some JavaScript code to execute as soon as a resource is loaded, we can register a handler with that JavaScript code to the corresponding load event.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

Load Event Example: A common use case is when we want to manipulate a webpage as soon as it is loaded.

A

document.addEventListener(“DOMContentLoaded”, function(event) {
console.log(“DOM fully loaded and parsed”);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

___ provide another mechanism for event-driven programming in JavaScript. These ___ are used in client-side code for animations or for automatic page refreshes.

A

Timers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Timer example

A

setTimeout(turnBackgroundRed, 10000);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

We can call the method ___ () on an event to prevent the default action for the event from taking place.

An example use case is calling this method on a submit event to prevent the submission of a form if the form validation fails, as shown in the following code snippet.

A

preventDefault

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

When an event is fired at an element that has parent elements, what happens if event handlers are defined at both the element and its parent?

A

The default behavior is that the event bubbles up the DOM tree until it gets to the root element, i.e., the html element. This is called the bubbling phase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

The event handler on any element can stop an event from bubbling up the DOM tree by calling the method of the event in question.

A

stopPropagation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

Is it also possible to define event handlers which are executed on the DOM tree starting with the html element and going down the tree until the element on which the event occurred is reached?

A

Yes, This is called the capturing phase and the event is said to trickle-down the DOM tree. Using stopPropagation stops an event from trickling down the DOM tree, similar to how this method stops an event from bubbling up. By default, event handlers are registered for the bubbling phase and registering handlers for the capturing phase is a lot less common.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

___ programming is an essential feature of modern JavaScript. It is widely used to build scalable, performant web apps. ___ features of JavaScript are used in both client-side and server-side programs.

A

Asynchronous

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

By default, JavaScript code run ___ in a single thread

A

synchronously

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Asynchronus or Synchronous?

Each function runs to completion before any other code is executed in the program.

A

Synchronous

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

___ means that the entire program is halted until that line of code finishes executing.

A

Blocking

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

Asynchronus or Synchronous?

non-blocking. As soon as an ___ function is called, the next line of code in the calling function can be executed.

A

Asynchronus

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

T or F: When the asynchronous function completes, its results can be accessed by the main thread using callbacks or via the newer features of Promises and await/async.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

Why Using Callbacks is Unsatisfactory

A

when our program needs to make multiple asynchronous calls that depend on each other (nested), implementing asynchronous functionality using callback functions can lead to hard-to-understand code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

A ___ is a JavaScript object that represents the result of an asynchronous operation whose results may not be available as yet.

A

Promise

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

When the asynchronous function successfully finishes, it fills in the Promise object with the result and sets its state to ___ . The promise is now said to have been ___ . The Promise is said to have resolved to this result value.

A

fulfilled

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

The asynchronous function returns a ___ object.

A

Promise

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

The initial state of this Promise object is ___ meaning it does not yet have a result.

A

pending

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

When the asynchronous function fails due to an error, it will not produce a value. In this case, the state of the Promise object is set to ___. The promise is said to have been ___.

A

rejected

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

Once the state of the Promise objects is set to either the fulfilled or rejected, it is said to have been ___.

A

settled

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

T or F: When we call a function which returns a promise, we provide functions that will be executed when the promise settles.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

Using the ___ method on the promise, we provide a function that will be called when the promise returns a result, i.e., it is fulfilled. If the function provided to ___ returns another promise, we can process its result by calling the ___ method again

A

then()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

Using the ___ method on the promise, we provide a function that will be called when the promise fails, i.e., it is rejected.

A

catch()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

The function ___ has one required parameter identifying the resource for which an HTTP request would be sent. By default, ___ sends a request with the GET method. ___ returns a promise.

A

fetch()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

fetch() example

A

function getData(url) {
return fetch(url)
.then(response => response.text())
.then(data => addData(data))
.catch(error => console.error(error));
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

when one asynchronous function returns a promise which is then passed to another asynchronous function that in turn returns a promise, we can chain these function calls by using multiple ___ methods.

A

then()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

The ___ keyword takes a promise and waits for the promise to be settled. If the promise is fulfilled, the resolved value is returned.
If the promise is rejected, an exception is thrown with the rejection value of the promise.

A

await

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

we can only use ___keyword in a function that is declared with the ___ keyword

A

await

async

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

An ___ function is executed asynchronously which means that the call to the ___function returns immediately. A __ function always returns a promise.

A

async

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

async example

A
async function getData(url) {
    try {
        const response = await fetch(url);
        const data = await response.text();
        addData(data);
    } catch (error) {
        console.error(error)
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

When we write code in an ES module, only those functions, classes or variables that are explicitly exported using the keyword export are available outside the module. Such exports are called named ___. Everything else is inaccessible to code outside the module.

A

exports

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

We ___ named features from a module using the ___ statement along with the name of the features we want to ___ and the URL of the file containing the module.

A

import

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

We can import all the exported features into an object by using __.

A

*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

We can tag at most one feature in an ES module with the export ___ tag. The benefit of default exports is that the syntax for importing the default feature is very simple.

A

default

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

With CommonJS modules, we import features using the ___ built-in function. This function takes one argument which identifies the module or the local file we want to import into our code.

A

require()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

In CommonJS, the function ___ reads the module/file passed to it as an argument. It executes this module/file and returns the ___object from the file.

A

require()

exports

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

IUSING ES Modules with node:

Use the extension \_\_ for files which want to export modules using ES syntax and for files which want to import modules using ES syntax.
Use the extension \_\_ for such files and also add a top level property "type" with the value "module in the file package.json.
A

.mjs

.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

Express: To serve static files, we added the following statement to our server programs:
app.use(express.___(‘public’));

A

static

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

Express: When our server program needed to process forms, we added the following statement to our program
app.use(express.___({extended: true}));

A

urlencoded

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

A ___is simply a function that Express applies to an HTTP request in our Express programs. We can think of an Express program as a pipeline of ___functions which are applied to an HTTP request.

A

middleware

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

Most middleware functions take three arguments:

A
  1. request
  2. response
  3. next()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

Another form of middleware functions, called Error-handling middleware, takes four arguments:

A
  1. error
  2. request
  3. response
  4. next()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

Each middleware function in an Express app is associated with a ___(or route). A middleware function applies to an HTTP request only if that function’s ___matches the URL of the request.

A

path

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

T or F: The middleware functions with routes matching a request’s URL are applied in the exact order of how they appear in the code of our Express app, thus setting up a pipeline of functions.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

A middleware function can pass the request to the next middleware function in the pipeline by calling the ___ function that is provided to it as an argument.

A

next()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

The pipeline of middleware functions terminates when:

A
  1. All middleware has been applied to the request

2. There’s no next() call

112
Q

What happens if a middleware function is executed, but it does not call next() and does not send back a response?

A

In this case, because next() has not been called the pipeline terminates and no other middleware function will be executed. However, no response has been sent back to the client program which sent the request. This will cause the client to ultimately timeout and report an error, e.g., a network error.

113
Q

middleware example

A
// route handler 1
app.get("/", (req, res, next) => {
    console.log("Handling / and calling next");
    next();
});
// route handler 2
app.get("/abcd", (req, res, next) => {
    console.log("Handling abcd and calling next");
    next();
});
// route handler 3
app.get("/abcd", (req, res, next) => {
    console.log("Handling abcd and not calling next");
    res.send(`typeof next is ${typeof (next)}`);
});
114
Q

___ is intended for binding middleware to your application. The path is a “mount” or “prefix” path and limits the middleware to only apply to any paths requested that begin with it.

A

app.use()

115
Q

__ is part of Express’ application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

A

app.get()

116
Q

A ___is an organized collection of data while a ____ is the software used to manage databases

A

database

database management system (DBMS)

117
Q

Two important features of A DBMS

A
  1. supports efficient CRUD

2. execution of CRUD operations for a large number of users

118
Q

T or F: Relational DBMS, such as Oracle, SQL Server, PostgreSQL, MySQL, etc., are the most common types of DBMS in current use.

A

True

119
Q

In a ___ DBMS, data is organized as tables.

A

relational

120
Q

In a ___-oriented DBMS, also simply called a ____DBMS, data is stored as a ____in a format such as JSON or XML.

A

document

121
Q

T or F: Document-oriented DBMS, such as MongoDB, Amazon’s DocumentDB, Couchbase, Google’s Firestore, are newer than relational DBMS

A

True

122
Q

In a ___ DBMS, data is added to a collection.

A

Document

123
Q

___DBMS support a standard query language called SQL (Structured Query Language). SQL provides support for all CRUD operations on tables, as well as support for creating, updating and dropping tables.

A

Relational

124
Q

___ DBMS started out as explicitly rejecting SQL and were associated with a movement termed NoSQL DBMS. CRUD operations were, and continue to be, supported via functions provided by the document DBMS.

A

Document

125
Q

useful commands we can run using mongo: show dbs

A

List all databases in the MongoDB server

126
Q

useful commands we can run using mongo: use db_name

A

Use the database db_name. Substitute db_name with the name of database you want to connect to. If the database does not exist, it will be created.

127
Q

useful commands we can run using mongo: show collections

A

List all the collections in the current database

128
Q

T or F: mongo does not include a JavaScript API

A

False, it does. which we can use to create and manage collections, as well as perform CRUD operations on a collection

129
Q

db.getCollectionNames()

A

List all the collections in the current database

130
Q

db.createCollection(…)

A

Create a new collection

131
Q

db.coll.insert(…)

A

Create a document in the collection coll. The argument is a JSON object. MongoDB creates and associate a unique object ID value with each document. This value is stored in the property _id.

132
Q

db.coll.findOne()

A

Return a single document at random from coll.

133
Q

db.coll.find()

A

Return all documents from coll that match the criteria passed in the argument. If the number of documents exceeds 20, then batches of up to 20 documents are returned. Type it to get the next batch

134
Q

db.coll.update({“_id”: ObjectId(“123”)}, {…} )

A

Update the document with object ID 123.

135
Q

db.coll.remove({“_id”: ObjectId(“123”)})

A

Delete the document with object ID 123.

136
Q

db.coll.remove({ … })

A

Delete all the documents matching the criteria passed in the argument.

137
Q

The basic idea of ___ is that we decompose the functionality of an app with a GUI into 3 layers, model, view, and controller.

A

MVC (Model-View-Controller)

138
Q

The ___of an app corresponds to the layer that manages the application’s data.

A

model

139
Q

In apps developed using languages with support for object-orientation, the model will include:

A
  1. Classes in the app that represent the data in the database.
  2. Code that maps the data in the database to these classes and maps the classes to the data in the database.
  3. Code that executes CRUD operations on the DBMS.
140
Q

The ___is the layer of the app that displays data from the app. In a web app, the ___is ultimately rendered in HTML and CSS. The ___does not directly interact with the model. Instead, it will send information about a user’s interaction with the ___to the controller.

A

view

141
Q

The ___is the layer of the app that connects the view to the model. The ___handles requests from the view layer. It determines how to process the request. It decides how to involve the view and model layer in processing the request, including how the view and the model might be updated due to the request.

A

controller

142
Q

In an Express app, the controller layer is implemented by the ____, which

  1. Receive requests
  2. Call functions to perform CRUD operations on the model layer
  3. Send back responses that update the view
A

route handlers

143
Q

Mongoose is used in the ___layer of a web app.

A

model

144
Q

___ is an object-document mapper (ODM) that maps between classes and objects in our JavaScript code and the documents stored in MongoDB

A

Mongoose

145
Q

In Mongoose, ___and ___are the main concepts for mapping between documents in MongoDB and objects in our JavaScript code.

A

schemas

models

146
Q

A ___represents the properties of a collection in MongoDB.

A

schema

147
Q

In Mongoose, the ___is a JavaScript class which represents documents of a particular collection. Call the method ___on the mongoose object passing it two parameters:

  1. The name of the JavaScript class that Mongoose will generate
  2. The schema which Mongoose will use to generate this class.
A

model

148
Q

We can use the model class to create documents by using JavaScript’s built-in support for object-oriented programming, i.e., we can create documents by calling the class constructor with the ___keyword.

A

new

149
Q

Example: Creating Documents Using the Model Class

A

const Movie = mongoose.model(“Movie”, movieSchema);

const movie = new Movie({ title: “Fargo”, year: 1996, language: “English” })

150
Q

Example: Schema Definition

A
const movieSchema = mongoose.Schema({
	title: { type: String, required: true },
	year: { type: Number, required: true },
	language: { type: String, required: true }
});
151
Q

This file contains the model layer.
It uses Mongoose to connect to MongoDB.
It contains the 4 functions implementing the CRUD operations and exports these functions to make them available for use outside this file

A

model.js

152
Q

This file includes our Express code and implements the route handlers.
It imports movies_model.mjs and the route handlers call the relevant functions in movies_model.mjs.

A

controller.js

153
Q

Create Operation in the Model

A
createMovie = async (title, year, language) => {
      // Call the constructor to create an instance of the model class Movie
      const movie = new Movie({ title: title, year: year, language: language });
      // Call save to persist this object as a document in MongoDB
      return movie.save();
  }
154
Q

Retrieve Operation

A
findMovies = async (filter, projection, limit) => {
      const query = Movie.find(filter)
          .select(projection)
          .limit(limit);
      return query.exec();
  }
155
Q

___ is a parameter used to match documents. Mongoose converts the ___into a Boolean condition and checks this condition on each document.
If the condition evaluates to false for a document, then it will not be included in the result. If this parameter is not provided, it defaults to an empty condition which evaluates to true for every document in the collection.

A

filter

156
Q

In mongoose, A space-separated list of the properties of the document which we want to be included in the result. If it is not provided, all properties of the document are included.

A

projection

157
Q

In mongoose, This parameter allows further tailoring of what the result should look like.

A

options

158
Q

Update Operation

A
replaceMovie = async (id, title, year, language) => {
      const result = await Movie.replaceOne({ _id: id }, { title: title, year: year, language: language });
      return result.nModified;
  }
159
Q

Delete Operation

A
deleteById = async (id) => {
      const result = await Movie.deleteOne({ _id: id });.
      return result.deletedCount;
  }
160
Q

In Mongoose, We can require that the result of query contains ONLY those documents that match all of the specified conditions by calling the and method on a query with an array containing all the filters we want to apply on the documents. Note that if the array is empty then all the documents will match the query.

A

and

query.and(filters);

161
Q

In Mongoose, We can require that the result of query contains only those documents that match ANY of the specified conditions by calling the or method on a query with an array containing all the filters we want to apply on the documents. Note that if the array is empty then all the documents will match the query.

A

or

  query.or(filters);
162
Q

While the POST method is used for create operations, the HTTP ___method is used for update operations. A prescribed use of the ___method is for HTTP requests in which a resource is completely replaced by the data in the HTTP request with the ___method.

A

PUT

163
Q

The prescribed use of the ___ method is for partial updates of a resource, unlike PUT which is used for completely replacing the resource.

A

PATCH

164
Q

The prescribed use of the ___ method is to delete a resource.

A

DELETE

165
Q

the ___ method is not related to CRUD operations. The ___method is similar to GET in that it requests a resource for retrieval. However, the response to a request using the ___method does not include the resource, but only includes the status line and the HTTP response headers. This is used by clients, such as browsers, to determine if the resource in their cache is still fresh, or should they now issue a GET request for the resource.

A

HEAD

166
Q

The term ___ is used for the combination of a URL and an HTTP method. Two requests that have the same URL, but different HTTP methods, are considered two different ___. In Express it is simple to define routes based on the combination of a URL and HTTP method.

A

endpoint

167
Q

___ are used by the client and the server to pass additional information about the HTTP request or the HTTP response.

A

HTTP headers

168
Q

when an HTTP response contains body, the client needs to know how to interpret these bytes send by the server. This information is conveyed by using values from a standard called ___

A

Multipurpose Internet Mail Extensions or MIME type

169
Q

T or F: The typical structure of a MIME type is of the form type/subtype, i.e., two strings separated by a /.

A

True

170
Q

MIME: The ___indicates a general category. The __indicates the exact type of data within that category

A

type

subtype

171
Q

The ___ header is used in HTTP requests by a client to tell the server about the types of data the client can handle. In general, the value of the ___header is one or more MIME types separated by commas.

A

Accept

172
Q

The__ header can be used in both HTTP requests and HTTP responses. HTTP responses with a body include the ___ header to tell the client the MIME type of the body in the response.

A

Content-type

173
Q

T or F: The most common MIME type for POST bodies is application/x-www-form-urlencoded which is used when we submit a form with its action set to POST. This is also referred to as HTML form encoding or URL form encoding

A

True

174
Q

100-199:

A

Informational responses

Status codes in this category indicate that the request was received and the server is continuing to process it.

175
Q

200-299:

A

Successful responses

176
Q

200

A

OK

177
Q

201

A

Created

178
Q

204

A

No Content

179
Q

300-399:

A

Redirection

180
Q

Moved Permanently

A

301

181
Q

Found

temp moved

A

302

182
Q

See Other

server direct to another resource

A

303

183
Q

Not Modified

A

304

184
Q

400-499:

A

Client errors

185
Q

Bad Request

A

400

186
Q

Unauthorized

A

401

187
Q

Forbidden

A

403

188
Q

Not found on server

A

404

189
Q

500-599:

A

Server errors

190
Q

500

A

internal server error

191
Q

502

A

Bad Gateway

192
Q

503

A

Service Unavailable

193
Q

Reques Obj: This object contains the query parameters as name-value pairs.

A

req.query

194
Q

Reques Obj: This object contains the body of the request as name-value pairs.

A

req. body

app. use(express.urlencoded({extended: true}));

195
Q

Request Obj: This object contains all the request headers as key-value pairs, where the keys are the header names and values are the header values.

A

req.headers

for (const property in req.headers) {
console.log(${property}: ${req.headers[property]});
}

196
Q

Response object: We can set response headers using this method. However, typically we do not manually set any headers, except perhaps Content-Type.

A

res.type(type)

197
Q

Response object: A convenient method to set the Content-Type header instead of using res.set to set the header. By default, Express sets the content type in the response to text/html. But we can set the appropriate MIME type by using this method

A

res.type(type)

198
Q

Response object: By default, Express sets the status code to 200. If we want to set the status code to some other value, we can use this method.

A

res.status(code)

199
Q

Response object: Calling this method sends the response to the client with the response body set to the specified argument. However, if we are sending back JSON in the response body, we should use res.json.

A

res.send(body)

200
Q

Response object: This method sends back JSON to the client and sets the Content-Type header to application/json. Using this method, we can send any JSON value as the response body, including JSON arrays.

A

res.json(json)

201
Q

The HTTP protocol is ___. What this means is that when two requests are sent one after the other by the same user of a web app, HTTP does not maintain any information that links these two requests as coming from the same user. If we think about how we use various web applications this will seem problematic.

A

stateless

202
Q

Web apps overcome the statelessness of the HTTP protocol by using HTTP ___and HTTP __. This allows web apps to link different requests as coming from the same user.

A

cookies

sessions

203
Q

An HTTP ___ is a small piece of data that is created by a web server and sent to the user’s web browser for storage. The browser can send this HTTP ___in later requests to this web server thus identifying who this request is coming from.

A

cookie

204
Q

By linking together multiple requests from the same user, HTTP ___allow web apps to overcome the stateless nature of the HTTP protocol.

A

cookies

205
Q

When the server wants the client to store a cookie, the server sends the cookie in the response header containing the name-value pair for the cookie.

A

Set-Cookie

206
Q

Setting a cookie

A

res.cookie(‘language’, ‘English’)

207
Q

This option specifies the time in milliseconds the client should keep the cookie before deleting it. If this value is not specified, the cookie will be deleted when the browser is closed.

A

maxAge:

208
Q

Delete a cookie

A

E.g., res.clearCookie(‘language’) will delete the cookie named language.

209
Q

Get value of cookie

A

E.g., req.cookies.language will give the value of the cookie named language if that cookie was sent by the client. Otherwise, we will get the value undefined.

210
Q

To prevent tampering of a cookie’s value by the user, we can use ___cookies. If the value of a ___cookie has been tempered with, the cookie-parser will recognize this and the server will reject the value of the cookie

A

signed

211
Q

To use signed cookies, we need to provide a ___to the cookie parser middleware. The cookie parser middleware will then use this ___to sign the cookie.

A

secret

import cookieParser from ‘cookie-parser’;
app.use(cookieParser(‘sOme4rAnDom$tringCangohere’));

212
Q

Once the cookie parser has been set up with a secret, we can create signed cookies by passing the option {___} when setting the cookie:

A

signed: true

res. cookie(‘favorite_icecream’, ‘mintChocolateChip’, {signed: true });

213
Q

We obtain signed cookies, by using the property ___on the request object:

A

signedCookies

const favoriteIcecream = req.signedCookies.favorite_icecream;

214
Q

When a user logs in, the website creates a ___object on the server and sends a cookie with a unique identifier to the user. When subsequent requests contain a cookie with this unique ___ID, the website can link requests from this user and can store data relevant to this user’s interaction with the website in the ___object.

A

session

215
Q

The express-___ middleware takes a configuration object as a parameter.

A

session

216
Q

The string to be used to sign the cookie created for the session ID.

A

secret

217
Q

Options for the cookie to be created for the session ID.

A

cookie

218
Q

If this is not specified, the default name is connect.sid.

A

identifier

219
Q

The name of the cookie that will store the value of the unique session identifier. If this is not specified, the default name is connect.sid.

A

key

220
Q

By default, Express stores session objects in memory. This is called ___

A

memory store

221
Q

The path this cookie applies to.

A

path:

222
Q

The value true specifies that the cookie will only be sent over a secure, i.e., HTTPS, connection.

A

secure:

223
Q

The value true specifies that cookie should be signed, as explained later in this section.

A

signed:

224
Q

By default, Express stores session objects in memory. This is called ___

A

memory store

225
Q

The term ___ is used for an API that can be accessed using the HTTP protocol

A

web service

226
Q

___ download the HTML, CSS, and JavaScript for a web application from the web server to the browser exactly once. Once the web application is loaded into the browser, then JavaScript code makes changes to the DOM so that the user feels that they are navigating to a different page. After the initial bundle of files has been downloaded, the web app communicates with the server for various data operations, e.g., to fetch new data, or to update, create and delete data.

A

Single Page Applications (SPAs)

227
Q

In REST, A ___manages collections of resources. A ___should expose collections and resources to the clients using unique URLs. A ___should support CRUD operations by providing a set of HTTP methods as follows:

A

server

228
Q

In REST, The server should be __. Specifically, each HTTP request happens in isolation.

A

stateless

229
Q

T or F: an API is RESTful if the server used information from the previous request to service the next request from the client.

A

False, it is not restful

230
Q

___specifies a certain pattern of URLs to identify each collection and each resource within a collection. CRUD operations are carried out using specific HTTP methods and the server implementing a ___API should not maintain state about client requests.

A

REST

231
Q

___ is the measure of the quality of a user’s experience when interacting with a product or system

A

Usability

232
Q

Usability is a combination of factors that affect the user’s experience with a product or system, including:

A
  1. Ease of Learning
  2. Efficiency of use
  3. Memorability
  4. Error Frequency and severity
  5. subjective satisfaction
233
Q

T or F: Usability is important for any product because if the users of the product cannot achieve their goals satisfactorily, they are likely to seek alternative products.

A

True

234
Q

T or F: Poor usability will NOT lead to wasted time, reduced productivity and increased frustrations, all of which have a negative impact on the organization.

A

False, it does

235
Q

____ is a methodical approach to producing a web app (or any product) that achieves its user’s goals while providing easy learnability, efficient use, memorability, error-free use and subjective satisfaction.

A

Usability engineering

236
Q

This is about the limit for a system to respond so that an interaction feels instantaneous to a user.

A

0.1 second

237
Q

This is about the limit for a user’s flow of thought to remain uninterrupted.
If the delay is longer than it, the user will consciously notice the delay.

A

1 second

238
Q

This is about the limit for keeping the user’s attention focused on the actions at hand.
If the delay is longer than it, the user will begin to think about other tasks.

A

10 seconds

239
Q

For shorter delays between ___ and ___ seconds, just displaying a busy cursor is sufficient.

A

2 and 10

240
Q

For delays longer than __ seconds, consider displaying a progress bar displaying percent-completion of the task. If there isn’t a way to determine percent-completion, displaying messages about the actions being done is helpful to the user.

A

10

241
Q

The number of levels a user has to traverse to get to the content of interest is termed ____ Level. As the ____ level goes up, it becomes more difficult for the users to return to a particular web page they had found interesting.

A

Content Depth

242
Q

When designing the user interface of a web app, we should consider the impact of different ___ devices on the user experience

A

input

243
Q

The goal of ___ is to uncover problems the users may encounter so that these problems can be fixed.

A

Usability Testing

244
Q

This testing is done by having the users perform a variety of tasks with a partial or complete implementation of the web app. The users’ interactions with the web app are recorded using a screen capture tool, e.g., Camtasia. Additionally, a webcam might be used see the users’ face and their words might be record.

A

Usability Testing

245
Q

Testing usability with a ____ is a cheap and practical way to test usability.

A

paper prototype

246
Q

___ is the property of a system to increase in size and capacity while continuing to achieve its functional and performance goals in a cost-effective manner.

A

Scalability

247
Q

3 important metrics of scalability

A
  1. response time
  2. throughput
  3. reliability
248
Q

The time between sending a request and receiving a response.

For example, when a user creates a new movie in our example movie app, this is the time between them hitting the button to add the movie and receiving a response about the movie being added by the web app.

A

Response time

249
Q

The number of operations completed per unit time.

For example, if a web app completes 500 requests (from any number of web browsers) per second, then its throughput is 500 per second.

A

Throughput

250
Q

The percentage of operations successfully completed.

A

reliability

251
Q

Whenever a ____uses a very large amount of data, we should aim to move the ___ to the data, instead of moving the data to the ___.

A

computation

252
Q

Using this technique, in particular when interacting with the DBMS, is the most important thing we can do to build scalable apps.

A

Local computation

253
Q

Since communicating requests and responses over the internet is a major component of the response time of a web app, sending requests and responses with ___ size helps improve the performance and scalability of a web app

A

minimal

254
Q

When it comes to ____content, one technique to minimize the size of messages is by using a concise data format such as JSON instead of XML.

A

dynamically generated

255
Q

___ is a markup language similar to HTML in syntax. But it is more powerful than HTML and allows user-defined tags which can be used to define our own markup languages.

A

XML

256
Q

____means that after we fetch or compute some data, we save it so that we don’t have to fetch or compute it again.

A

Caching

257
Q

costs associated with caching.

A

A cache requires storage,

the cache needs to be managed.

258
Q

The browser app can act on the following HTTP response headers to decide when and how to cache static content:

A
  1. Cache-Control or Expires header

2. Etag or Last-Modified header

259
Q

tells the browser whether the document should be cached, and using a max-age value tells the maximum time the document should be kept in the cache.

A

Cache-Control header

260
Q

specifies a specific expiration date and time for the document.

A

Expires header

261
Q

provides versioning information.

A

Etag Header

262
Q

specifies when the resource was last modified. considered a fallback to the etag header

A

Last-modified header

263
Q

two primary architectures for scaling a web app, scale-up or scale out.

A
  1. Scale Up

2. Scale Out

264
Q

___ means expanding capacity by using a server machine that is more powerful, i.e., it has a faster CPU or more CPU cores, more memory, etc. ___ can work up to a certain point because there is a limit on how powerful a single server machine can be.

A

Scaling up

265
Q

____ means expanding capacity by adding more instances of the server.

A

Scaling out

266
Q

T or F: Scaling up is usually more cost-effective because instances can be added or removed as the loads goes up and down.

A

False, scale out

267
Q

T or F: Scaling out can also make the app more fault-tolerant. If one instance fails, the other instances can still process requests.

A

True

268
Q

T or F: As developers, we must write our apps keeping in the mind the possibility of scaling up.

A

False, scale out

269
Q

____ distribute work among them multiple web servers when handling requests for the same URL.

A

load balancers

270
Q

T or F: When developing apps that might use scaling out, we should not store any state in the web app.

A

True: The reason for this is that one request from the same user may be sent by the load balancer to one instance of the web server, while another request may be sent to another instance. If there is any state that is kept in the web app, then it will not be accessible when the request is routed to a different server

271
Q

T or F: To build scalable web apps, we must maintain state in local variables in our app.

A

False, we must NOT.

Instead, we should use persistent shared storage, such as a DBMS, to maintain state. This allows state to be shared correctly by multiple instances of our web app running on different web servers.

272
Q

Being able to verify the identity of the user.

A user has to provide some sort of credentials.

A

Authentication

273
Q

Deciding to give access to a service/resource to a user.

A

authorization

274
Q

3 key security objectives

A
  1. confidentiality
  2. integrity
  3. availability
275
Q

___ involve inserting something into the web app code that doesn’t belong there.

A

Injection attacks

276
Q

5 major Web Security Concerns

A
  1. Logging of URLs
  2. Impersonation
  3. Man-in-the-middle
  4. Network Attacks
  5. Injection Attacks