Final P2 Flashcards
form tag itself has two very important attributes.
- 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
percent-encoding or URL encoding
certain special characters that have a specific meaning within URLs are encoded with other characters
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.
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.
T or F: Unless we use the HTTPS protocol, which encrypts the HTTP communication, an intruder can see the body of a POST request.
True
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.
True
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.
False: GET
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
Express
GET route handler example
app.get(“/review”, (req, res) => {
console.log(req.query);
res.send(req.query);
});
POST route handler example
app.post(“/review”, (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.use(express.urlencoded({
extended: true
}));
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.
True
CSS selector
selects the HTML element to which the rule applies
CSS format
h1 {
color: red;
font-size: 25pt;
}
CSS: The universal selector *
matches all elements
CSS: The ___selector matches elements based on the element ___
type
CSS: The ___ selector selects the single element with a matching __ and is of the form #id
ID
CSS: The ___ selector selects all elements in which the attribute class has that value
class
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.
True
CSS: Is it possible to specify rules that apply to multiple selectors.?
Yes, This is done by specifying multiple selectors separated by commas.
CSS: We can specify selectors that select elements based on their location in the document
combinator selector
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.
Complex Selector
CSS also supports selectors that are based on the state of an element
CSS Pseudo Selectors
selector:pseudo-class {
property: value;
}
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.
True
CSS: Rule Precedence
- Later rules overrule earlier rules.
2. Rules with a more specific selector take precedence over those with more general selectors.
Colors in CSS are represented in three ways.
- Hex (hexadecimal) values in the form of #RRGGBB.
- Decimal values in the form of rbg(x, y, z)
- Named colors
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.
True
The most commonly used relative units are __ and __.
- em
2. rem
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.
True
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.
True
Size Properties in the Box Model
- Element (width/height)
- Padding (padding-top, etc.)
- Margin (margin-top, etc.)
- Border (can specify color, style, width)
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.
True
T or F: With relative positioning, the browser figures out where something should to be positioned using its default positioning algorithm.
False: static
T or F: Elements with static positioning are moved in relation to where they would be placed by the static positioning.
False: relative
T or F: Elements with absolute positioning are positioned in relation to the parent element.
True
T or F: Elements with fixed positioning are positioned with respect to the document window
True
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.
True
T or F: The DOM (Document Object Model) is the model that a browser uses to render a web page
True
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.
False: This allows us to write programs to DYNAMICALLY access
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.
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.
T or F: The object ___ represents the browser window and the object ___ represents the webpage currently loaded in this browser window.
- window
2. document
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.
True
DOM tree includes nodes of the following type:
- Document
- Document Type
- Element
- Attribute
- Text
Any node that has one or more children has the following properties:
- firstElementChild
- lastElementChild
- nextElementSibling
- previousElementSibling
- children
- parentNode
T or F: All of these are methods for searching for elements:
- getElementById
- getElementsByTagName
- getElementsByClassName
- querySelector
True
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.
True
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.
True
Nodes of type element have a property named ___which get the HTML markup within an element.
innerHTML
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.
- textContent
2. innerHTML
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
True
Adding nodes in a DOM tree is a two step process:
- Create the node by calling the appropriate method on the document object.
- 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.
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.
True
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.
True
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.
True
the method ___ and pass it the node we want to remove as an argument
removeChild()
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?
event-driven programming
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.
True
Event handling requires specifying 3 things
- What happened, i.e., what is the event of interest?
- Where did this event occur, i.e., what is the element of interest?
- What to do, i.e., what JavaScript code to invoke when the event occurs on this element?
Types of DOM events that should be handled
- mouse-related events
- keyboard-related events
- focus-related events
- form submission events
- Input event
- page related events
- timer events
There are two ways to register an event handler to execute when an event occurs on an element.
- Register the JavaScript code inline, as the value of an attribute with the name of the event (not recommended).
- Register the JavaScript code using the DOM API.
Registering an event handler on an element: Register the JavaScript code using the DOM API format
myElem.addEventListener(‘click’, mouseClick)
Example: Registering an Event Handler
// 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); };
T or F: We remove an event handler from an element by calling the method removeEventListener on this element.
True
Example: Removing an Event Handler
function unbindButton() { document.getElementById('backgroundChanger').removeEventListener('click', changeColor); }
T or F: When an event is raised, the browser cannot pass an object corresponding to this event to our handler.
False, it can
Some of the most important properties of this object include the following:
- type: the name of the event, e.g., click, mouseup, etc.
- timeStamp: the time that the event was created.
- target: the element that dispatched the event.
- currentTarget: the element on which the event listener was registered.
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.
True
Load Event Example: A common use case is when we want to manipulate a webpage as soon as it is loaded.
document.addEventListener(“DOMContentLoaded”, function(event) {
console.log(“DOM fully loaded and parsed”);
});
___ provide another mechanism for event-driven programming in JavaScript. These ___ are used in client-side code for animations or for automatic page refreshes.
Timers
Timer example
setTimeout(turnBackgroundRed, 10000);
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.
preventDefault
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?
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.
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.
stopPropagation
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?
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.
___ 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.
Asynchronous
By default, JavaScript code run ___ in a single thread
synchronously
Asynchronus or Synchronous?
Each function runs to completion before any other code is executed in the program.
Synchronous
___ means that the entire program is halted until that line of code finishes executing.
Blocking
Asynchronus or Synchronous?
non-blocking. As soon as an ___ function is called, the next line of code in the calling function can be executed.
Asynchronus
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.
True
Why Using Callbacks is Unsatisfactory
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
A ___ is a JavaScript object that represents the result of an asynchronous operation whose results may not be available as yet.
Promise
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.
fulfilled
The asynchronous function returns a ___ object.
Promise
The initial state of this Promise object is ___ meaning it does not yet have a result.
pending
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 ___.
rejected
Once the state of the Promise objects is set to either the fulfilled or rejected, it is said to have been ___.
settled
T or F: When we call a function which returns a promise, we provide functions that will be executed when the promise settles.
True
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
then()
Using the ___ method on the promise, we provide a function that will be called when the promise fails, i.e., it is rejected.
catch()
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.
fetch()
fetch() example
function getData(url) {
return fetch(url)
.then(response => response.text())
.then(data => addData(data))
.catch(error => console.error(error));
}
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.
then()
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.
await
we can only use ___keyword in a function that is declared with the ___ keyword
await
async
An ___ function is executed asynchronously which means that the call to the ___function returns immediately. A __ function always returns a promise.
async
async example
async function getData(url) { try { const response = await fetch(url); const data = await response.text(); addData(data); } catch (error) { console.error(error) } }
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.
exports
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.
import
We can import all the exported features into an object by using __.
*
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.
default
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.
require()
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.
require()
exports
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.
.mjs
.js
Express: To serve static files, we added the following statement to our server programs:
app.use(express.___(‘public’));
static
Express: When our server program needed to process forms, we added the following statement to our program
app.use(express.___({extended: true}));
urlencoded
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.
middleware
Most middleware functions take three arguments:
- request
- response
- next()
Another form of middleware functions, called Error-handling middleware, takes four arguments:
- error
- request
- response
- next()
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.
path
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.
True
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.
next()
The pipeline of middleware functions terminates when:
- All middleware has been applied to the request
2. There’s no next() call
What happens if a middleware function is executed, but it does not call next() and does not send back a response?
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.
middleware example
// 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)}`); });
___ 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.
app.use()
__ is part of Express’ application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:
app.get()
A ___is an organized collection of data while a ____ is the software used to manage databases
database
database management system (DBMS)
Two important features of A DBMS
- supports efficient CRUD
2. execution of CRUD operations for a large number of users
T or F: Relational DBMS, such as Oracle, SQL Server, PostgreSQL, MySQL, etc., are the most common types of DBMS in current use.
True
In a ___ DBMS, data is organized as tables.
relational
In a ___-oriented DBMS, also simply called a ____DBMS, data is stored as a ____in a format such as JSON or XML.
document
T or F: Document-oriented DBMS, such as MongoDB, Amazon’s DocumentDB, Couchbase, Google’s Firestore, are newer than relational DBMS
True
In a ___ DBMS, data is added to a collection.
Document
___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.
Relational
___ 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.
Document
useful commands we can run using mongo: show dbs
List all databases in the MongoDB server
useful commands we can run using mongo: use db_name
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.
useful commands we can run using mongo: show collections
List all the collections in the current database
T or F: mongo does not include a JavaScript API
False, it does. which we can use to create and manage collections, as well as perform CRUD operations on a collection
db.getCollectionNames()
List all the collections in the current database
db.createCollection(…)
Create a new collection
db.coll.insert(…)
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.
db.coll.findOne()
Return a single document at random from coll.
db.coll.find()
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
db.coll.update({“_id”: ObjectId(“123”)}, {…} )
Update the document with object ID 123.
db.coll.remove({“_id”: ObjectId(“123”)})
Delete the document with object ID 123.
db.coll.remove({ … })
Delete all the documents matching the criteria passed in the argument.
The basic idea of ___ is that we decompose the functionality of an app with a GUI into 3 layers, model, view, and controller.
MVC (Model-View-Controller)
The ___of an app corresponds to the layer that manages the application’s data.
model
In apps developed using languages with support for object-orientation, the model will include:
- Classes in the app that represent the data in the database.
- Code that maps the data in the database to these classes and maps the classes to the data in the database.
- Code that executes CRUD operations on the DBMS.
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.
view
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.
controller
In an Express app, the controller layer is implemented by the ____, which
- Receive requests
- Call functions to perform CRUD operations on the model layer
- Send back responses that update the view
route handlers
Mongoose is used in the ___layer of a web app.
model
___ is an object-document mapper (ODM) that maps between classes and objects in our JavaScript code and the documents stored in MongoDB
Mongoose
In Mongoose, ___and ___are the main concepts for mapping between documents in MongoDB and objects in our JavaScript code.
schemas
models
A ___represents the properties of a collection in MongoDB.
schema
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:
- The name of the JavaScript class that Mongoose will generate
- The schema which Mongoose will use to generate this class.
model
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.
new
Example: Creating Documents Using the Model Class
const Movie = mongoose.model(“Movie”, movieSchema);
const movie = new Movie({ title: “Fargo”, year: 1996, language: “English” })
Example: Schema Definition
const movieSchema = mongoose.Schema({ title: { type: String, required: true }, year: { type: Number, required: true }, language: { type: String, required: true } });
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
model.js
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.
controller.js
Create Operation in the Model
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(); }
Retrieve Operation
findMovies = async (filter, projection, limit) => { const query = Movie.find(filter) .select(projection) .limit(limit); return query.exec(); }
___ 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.
filter
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.
projection
In mongoose, This parameter allows further tailoring of what the result should look like.
options
Update Operation
replaceMovie = async (id, title, year, language) => { const result = await Movie.replaceOne({ _id: id }, { title: title, year: year, language: language }); return result.nModified; }
Delete Operation
deleteById = async (id) => { const result = await Movie.deleteOne({ _id: id });. return result.deletedCount; }
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.
and
query.and(filters);
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.
or
query.or(filters);
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.
PUT
The prescribed use of the ___ method is for partial updates of a resource, unlike PUT which is used for completely replacing the resource.
PATCH
The prescribed use of the ___ method is to delete a resource.
DELETE
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.
HEAD
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.
endpoint
___ are used by the client and the server to pass additional information about the HTTP request or the HTTP response.
HTTP headers
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 ___
Multipurpose Internet Mail Extensions or MIME type
T or F: The typical structure of a MIME type is of the form type/subtype, i.e., two strings separated by a /.
True
MIME: The ___indicates a general category. The __indicates the exact type of data within that category
type
subtype
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.
Accept
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.
Content-type
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
True
100-199:
Informational responses
Status codes in this category indicate that the request was received and the server is continuing to process it.
200-299:
Successful responses
200
OK
201
Created
204
No Content
300-399:
Redirection
Moved Permanently
301
Found
temp moved
302
See Other
server direct to another resource
303
Not Modified
304
400-499:
Client errors
Bad Request
400
Unauthorized
401
Forbidden
403
Not found on server
404
500-599:
Server errors
500
internal server error
502
Bad Gateway
503
Service Unavailable
Reques Obj: This object contains the query parameters as name-value pairs.
req.query
Reques Obj: This object contains the body of the request as name-value pairs.
req. body
app. use(express.urlencoded({extended: true}));
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.
req.headers
for (const property in req.headers) {
console.log(${property}: ${req.headers[property]}
);
}
Response object: We can set response headers using this method. However, typically we do not manually set any headers, except perhaps Content-Type.
res.type(type)
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
res.type(type)
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.
res.status(code)
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.
res.send(body)
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.
res.json(json)
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.
stateless
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.
cookies
sessions
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.
cookie
By linking together multiple requests from the same user, HTTP ___allow web apps to overcome the stateless nature of the HTTP protocol.
cookies
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.
Set-Cookie
Setting a cookie
res.cookie(‘language’, ‘English’)
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.
maxAge:
Delete a cookie
E.g., res.clearCookie(‘language’) will delete the cookie named language.
Get value of cookie
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.
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
signed
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.
secret
import cookieParser from ‘cookie-parser’;
app.use(cookieParser(‘sOme4rAnDom$tringCangohere’));
Once the cookie parser has been set up with a secret, we can create signed cookies by passing the option {___} when setting the cookie:
signed: true
res. cookie(‘favorite_icecream’, ‘mintChocolateChip’, {signed: true });
We obtain signed cookies, by using the property ___on the request object:
signedCookies
const favoriteIcecream = req.signedCookies.favorite_icecream;
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.
session
The express-___ middleware takes a configuration object as a parameter.
session
The string to be used to sign the cookie created for the session ID.
secret
Options for the cookie to be created for the session ID.
cookie
If this is not specified, the default name is connect.sid.
identifier
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.
key
By default, Express stores session objects in memory. This is called ___
memory store
The path this cookie applies to.
path:
The value true specifies that the cookie will only be sent over a secure, i.e., HTTPS, connection.
secure:
The value true specifies that cookie should be signed, as explained later in this section.
signed:
By default, Express stores session objects in memory. This is called ___
memory store
The term ___ is used for an API that can be accessed using the HTTP protocol
web service
___ 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.
Single Page Applications (SPAs)
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:
server
In REST, The server should be __. Specifically, each HTTP request happens in isolation.
stateless
T or F: an API is RESTful if the server used information from the previous request to service the next request from the client.
False, it is not restful
___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.
REST
___ is the measure of the quality of a user’s experience when interacting with a product or system
Usability
Usability is a combination of factors that affect the user’s experience with a product or system, including:
- Ease of Learning
- Efficiency of use
- Memorability
- Error Frequency and severity
- subjective satisfaction
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.
True
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.
False, it does
____ 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.
Usability engineering
This is about the limit for a system to respond so that an interaction feels instantaneous to a user.
0.1 second
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.
1 second
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.
10 seconds
For shorter delays between ___ and ___ seconds, just displaying a busy cursor is sufficient.
2 and 10
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.
10
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.
Content Depth
When designing the user interface of a web app, we should consider the impact of different ___ devices on the user experience
input
The goal of ___ is to uncover problems the users may encounter so that these problems can be fixed.
Usability Testing
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.
Usability Testing
Testing usability with a ____ is a cheap and practical way to test usability.
paper prototype
___ 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.
Scalability
3 important metrics of scalability
- response time
- throughput
- reliability
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.
Response time
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.
Throughput
The percentage of operations successfully completed.
reliability
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 ___.
computation
Using this technique, in particular when interacting with the DBMS, is the most important thing we can do to build scalable apps.
Local computation
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
minimal
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.
dynamically generated
___ 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.
XML
____means that after we fetch or compute some data, we save it so that we don’t have to fetch or compute it again.
Caching
costs associated with caching.
A cache requires storage,
the cache needs to be managed.
The browser app can act on the following HTTP response headers to decide when and how to cache static content:
- Cache-Control or Expires header
2. Etag or Last-Modified header
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.
Cache-Control header
specifies a specific expiration date and time for the document.
Expires header
provides versioning information.
Etag Header
specifies when the resource was last modified. considered a fallback to the etag header
Last-modified header
two primary architectures for scaling a web app, scale-up or scale out.
- Scale Up
2. Scale Out
___ 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.
Scaling up
____ means expanding capacity by adding more instances of the server.
Scaling out
T or F: Scaling up is usually more cost-effective because instances can be added or removed as the loads goes up and down.
False, scale out
T or F: Scaling out can also make the app more fault-tolerant. If one instance fails, the other instances can still process requests.
True
T or F: As developers, we must write our apps keeping in the mind the possibility of scaling up.
False, scale out
____ distribute work among them multiple web servers when handling requests for the same URL.
load balancers
T or F: When developing apps that might use scaling out, we should not store any state in the web app.
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
T or F: To build scalable web apps, we must maintain state in local variables in our app.
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.
Being able to verify the identity of the user.
A user has to provide some sort of credentials.
Authentication
Deciding to give access to a service/resource to a user.
authorization
3 key security objectives
- confidentiality
- integrity
- availability
___ involve inserting something into the web app code that doesn’t belong there.
Injection attacks
5 major Web Security Concerns
- Logging of URLs
- Impersonation
- Man-in-the-middle
- Network Attacks
- Injection Attacks