Web Dev 2 Final
Which statement is FALSE about the async function below? async function someFunc(num) { // some code omitted return num * num; }
"someFunc(2).then(alert);" is NOT a valid function call.
What Pug code segment produces HTML that displays even numbers from 2 to 10?
- let n = 0; while n < 10 - ++n if n % 2 == 0 p= n
Examine the following code. const app = express(); const router = express.Router(); router.get("/bing", handleRequest); app.use("/bang", router); What URL causes the handleRequest function to be called?
/bang/bing
What is output to the console? let population = new Map(); population.set("San Juan", 0.3); population.set("Tokyo", 9.3); population.set("Beijing", 20.5); population.set("San Juan", 0.7); population.delete("Tokyo"); console.log(population.size);
2
When a client sends an Express web API a new resource to add to the database, what status code should the server return to the client to acknowledge the resource was successfully created?
201
Which block of HTTP status codes indicate an error in the request?
400s
When using Mongoose, what does the code below do to employees that have a salary less than 25,000? Employee.updateMany({ salary: { $lt: 25000 } }, { $inc: { salary: 500 } }, function(err, result) { });
Adds 500 to all selected employees' salaries.
Which line of code instantiates Adele and the album 21? function PlayList(artist, album) { this.artist = artist; this.album = album; };
Adele = new PlayList("Adele", "21");
When using XMLHttpRequest, when is the HTTP request sent?
After calling send()
An Express server is listening on port 3000 with an API endpoint of /api/comicbooks. If a GET request is sent to http://localhost:3000/api/comicbooks, what is output to the console? const Comicbook = require("../models/comicbook"); const router = require("express").Router(); router.get("/", function(req, res) { let query = {}; if (req.query.publisher) { query = { publisher: req.query.publisher }; } Comicbook.find(query, function(err, comicbooks) { if (err) { console.log("error"); } else { console.log(comicbooks); } }); });
All comic books from the database
What is missing from the call to fetch() to POST a JSON-encoded movie to a movie API? const movie = { title: "Tenet", rating: "PG-13" }; const response = await fetch("/api/movie", { [ Select ] , headers: { [ Select ] }, [ Select ] });
Answer 1: method: "POST" Answer 2: "Content-Type": "application/json" Answer 3: body: JSON.stringify(movie)
How can the code segment ensure the movie API returns a valid movie with ID 456? let movie = { }; const response = await fetch("/api/movie/456");
Check value of response.ok
The browser decides what kind of content is returned from an HTTP request based on the _____.
Content-Type HTTP header
A developer is following BDD. After writing an initial specification composed of tests, what should the developer do next?
Create an initial implementation.
Which of the following does create-react-app NOT do?
Creates a simple RESTful web API
React is maintained as an open source project by ______.
Which statement is FALSE about function components?
Function components can maintain state.
What is output to the console? function changeThings(someMovie) { someMovie.rating = "G"; someMovie = { title: "Tron Legacy", rating: "PG-13" }; } let movie = { title: "Tron", rating: "PG" }; changeThings(movie); console.log(movie.rating);
G
Which HTTP request method should be idempotent?
GET
What is output to the console when the following code runs in a browser? var withVar = "Global declared with var"; let withLet = "Global declared with let"; console.log(withVar); console.log(withLet); console.log(window.withVar); console.log(window.withLet);
Global declared with var Global declared with let Global declared with var undefined
The chai-http package is used to test a web API. An excerpt is shown below. chai.request(server) .post('/api/students') .send(student) .end((err, res) => { res.should.have.status(400); res.body.should.be.a('object'); done(); }); }); What is the code likely testing?
If a POST request contains a student with invalid data
In a typical Node.js project structure, where is a Mongoose model stored?
In a separate directory for models
What type of data can be expected from a third party RESTful web API?
JSON or XML
A RESTful API supports updating movies with a PUT request. What must fetch() send in the HTTP request body to update an existing movie?
JSON-encoded movie with the same ID in the URL path
What is output to the console? function getSum(scores) { if (!Array.isArray(scores)) { throw new TypeError("Array error"); } if (scores.length != 2) { throw new RangeError("Length error"); } return scores[0] + scores[1]; } try { let sum = getSum([50, 60, 70]); console.log(sum); } catch (ex) { console.log(ex.message); }
Length error
What is one purpose of a package.json file?
Lists the project's dependencies
Which of the following allows for the reuse of code blocks in Pug?
Mixins
When using a RESTful web API, which request verb is used to create a new resource?
POST
In a RESTful web API, select ALL the verbs that typically expect the HTTP request to contain JSON in the request body.
POST PUT
What does "Ajax is used with polling" mean?
Periodically the browser sends an HTTP request to the web server to see if data is available.
What is missing to create a prototype method for PlayList called showCollection? function PlayList(artist, album) { this.artist = artist; this.album = album; }; _____ = function() { console.log("My playlist so far: " + this.artist + " : " + this.album); };
PlayList.prototype.showCollection
The fetch() method returns a _____.
Promise object
What is output to the console? function changeThings(someMovie) { someMovie.title = "Race"; someMovie = { title: "42", rating: "PG-13" }; } let movie = { title: "Greater", rating: "PG" }; changeThings(movie); console.log(movie.title);
Race
What does the following line of code do? localStorage.removeItem("name");
Removes the "name" key and associated value from storage
What is the purpose of the code below when creating unit tests? window.fetch = url => Promise.resolve({ ok: true, json: () => Promise.resolve(jsonResponse) });
Replaces fetch() temporarily so no HTTP requests are sent when testing.
What should a React component's render() do?
Return React elements
What part of a web application implements the V in a MVC architecture?
Template engine
Which statement is FALSE about automated testing of a RESTful web API?
Testing should normally be done against the production/live database.
In a MongoDB shell, what happens when the following command executes? db.movies.insert({ name: "What About Bob?", year: 1991 })
The document is added to the collection with a generated _id
Why do third-party web APIs often implement CORS?
To allow any website's page to send API requests
Why is a key sometimes needed to access a third-party web API?
To obtain a key, a developer must agree to restrictions on data received.
Refer to the pow() function and unit tests below. function pow(x, y) { let answer = x; while (y > 1) { answer *= x; y--; } return answer; } describe("pow function", function() { const testValues = [ [2, 3, 8], [1, 4, 1], [9, 0, 1] ]; for (let [x, y, answer] of testValues) { it(`${x} to power of ${y} is ${answer}`, function() { assert.equal(pow(x, y), answer); }); } }); What happens when the tests execute?
Two tests pass.
Which statement about unit testing is FALSE?
Unless XHR is mocked, Chai assert statements are likely to fail.
What is one purpose of npm?
Updates and installs packages for a Node.js project
How is a RESTful web service API called?
Using a URL and parameters
When would the function didNotWork() be called if the promise is fulfilled? promise.then(itWorked).catch(didNotWork);
When itWorked() throws an exception
_____ is a JavaScript object used to communicate with a web server.
XMLHttpRequest
In the following JSON, the data type associated with friends is _____. {"friends": [ {"name":"Bobby"}, {"name":"Celia"}, {"name":"Judy"} ]}
array
What Mongoose method call correctly deletes the employee with ID 123?
await Employee.deleteOne({ _id: 123 });
When using the chai-http package to test a web API, which function is likely NOT used when testing a GET route?
chai.send()
Complete the inheritance code below. class AnimePet extends AnimeCharacter { _____(name, owner, show) { _____(name, show); this.owner = owner; } }
constructor, super
sessionStorage stores _____ but localStorage stores _____.
data that persists until the browser or tab is closed, data indefinitely
What MongoDB command results in an empty students collection?
db.students.deleteMany({})
http://www.google.com and https://www.google.com are _____.
different origins
Examine the following code. app.use(f); app.use("/private", g); app.get("/private", h); app.get("/private/users", i); app.post("/private/users", j); app.get("/private/users/admin", k); Suppose the app receives the HTTP request below. Which middleware functions could potentially be called to handle the request (i.e., assuming each controller always passes control to the next middleware function). GET /private/users
f, g, i
Refer to the autos collection below. [ { "_id" : 100, "make" : "Ford", "model" : "Fusion", "year" : 2014, "price" : 13500 }, { "_id" : 200, "make" : "Honda", "model" : "Accord", "year" : 2013, "price" : 16900 }, { "_id" : 300, "make" : "Dodge", "model" : "Avenger", "year" : 2012, "price" : 10800 }, { "_id" : 400, "make" : "Toyota", "model" : "Corolla", "year" : 2013, "price" : 13400 } ] Complete the MongoDB command to return all documents. db.autos._____({ year: { _____ } })
find, $gte: 2012
React elements are _____, meaning that once the element is created, the element's attributes or children cannot be changed.
immutable
abSum is what type of function? function findSum(a, b) { let abSum = function() { return a + b; } return abSum(); }
inner
What PUG code generates the following HTML? <input type="text">
input(type="text")
Which line of code constructs Guam as an instance of AirportCode? class AirportCode { constructor(location, code) { this.location = location; this.code = code; } showCodes() { return "The airport code for " + this.location + " is " + this.code + "."; }; };
let Guam = new AirportCode("Guam", "GUM");
What expression iterates over all the animals properties? let animals = { "cat": 1, "dog": 1, "fish": 3, "hamster": 2 }; for (_____) { console.log(animal + " count = " + animals[animal]); }
let animal in animals
The variable discountPrice has _____. function musicTix(people, price) { if (people > 10) { var discountPrice = people * price * 0.9; return discountPrice; } return people * price; }
local scope
The variable findCost has _____. function musicTix(people, price) { var findCost = people * price; return findCost; }
local scope
What line completes the code segment below so the output is "the secret"? _____ console.log(localStorage.getItem("theKey"));
localStorage.setItem("theKey", "the secret");
In Express, the term routing refers to _____.
mapping a request to middleware functions
What is equivalent to the max() function below? function max(a, b) { if (a > b) { return a; } else { return b; } }
max = (a, b) => a > b ? a : b;
An Express web application uses a _____ function to perform an action in response to a request.
middleware
What code should be added to a module to export the app variable?
module.exports = app;
A movie web API returns a JSON-encoded array of movies. What is missing to output the first movie's title to the console? let response = await fetch("/api/movie"); let movies = await response.json(); console.log(_____);
movies[0].title
Complete the line of code so the negative numbers are filtered out. function positiveNumsOnly(numbers) { function isItPositive(positive) { return positive >= 0; } console.log("positive numbers are: " + _____); } let numbers = positiveNumsOnly([1, 0, -5, -96, 41, -99, -7]);
numbers.filter(isItPositive)
A POST request with URL http://localhost:8000/test is sent to an Express server. What two things are missing so the route below outputs "test" to the console? const router = express.Router(); router._____(_____, function(req, res) { console.log(req.param.name); });
post and "/:name"
An Express app receives a request for the URL below. How could a middleware function access the value of the year parameter? /book?year=2018&publisher=zyBooks
req.query.year
Suppose the express-session library is managing the app's sessions. Where can session data be found?
req.session
Suppose the express-session module is managing the app's sessions. Where can session data be found?
req.session
What can a middleware function check to see the requested URL?
req.url
What are the three parameters for an Express middleware function?
request, response, next
How would a script import the handlers module, which is located in the same directory as the script?
require('./handlers');
What line is missing from the following Express router code to return the book encoded as JSON? const router = express.Router(); router.get("/books", function(req, res) { const book = { title: "My Story", author: "Will Mar", isbn: 10, publishDate: new Date(2014, 10, 10), publisher: "NewHouse" }; _____ });
res.json(book);
The response variable is assigned with fetch(), which returns a JSON response. What method call returns an object that results from parsing the JSON response?
response.json()
A Mongoose _____ provides data types and properties for a MongoDB document, for example: { name: String, age: { type: Number, min: 18, max: 65 }, birthdate: { type: Date, default: Date.now }, interests: [ String ] }
schema
Which code segment defines a setter for the breed property, so that assigning to person1.breed sets person1.pet ? let person1 = { firstName: "Sophie", lastName: "Hernandez", age: 25, pet: "", _____ };
set breed(value) { this.pet = value; }
What does stringify() return? JSON.stringify({"friends": [ {"name":"Bobby", "age":20}, {"name":"Celia", "age":30}, {"name":"Judy", "age":21} ]}, ["friends", "age"]);
string with no names
What is missing to output "Title is The Hobbit"? class Book extends React.Component { render() { return <p>Title is <cite>{_____}</cite></p>; } } ReactDOM.render( <Book title="The Hobbit" />, document.getElementById("root"));
this.props.title
The responseReceivedHandler() function is registered as the XMLHttpRequest's load event handler with response type "json". The JSON response looks like: {"title":"Rocky", "rating":"PG", "year":"1976"} What is missing from responseReceivedHandler() to display the movie title? function responseReceivedHandler() { let movieInfo = document.getElementById("movieinfo"); if (this.status === 200) { movieInfo.innerHTML = "Title is <cite>" + ____.title + "</cite>"; } else { movieInfo.innerHTML = "Movie data unavailable."; } }
this.response
What is missing to complete the following code segment? let places = { woods: "Guam", beach: "PR", mountains: "Switzerland" }; try { console.log(places.rainforest); _____ "There might be an error"; } catch (error) { console.log(error); } _____ { console.log(places); }
throw, finally
Babel is a _____, a program that converts one language into another high-level language.
transpiler
Calling bankWithdraw(100); outputs _____ and returns _____. function bankWithdraw(amount) { let currentBalance = 500; let remaining = currentBalance; if (currentBalance >= amount) { let remaining = currentBalance - amount; console.log("$" + remaining); } return remaining; }
$400, 500
In the MongoDB query, how is every student EXCEPT Larry selected? { name: { _____: _____ } }
$ne, "Larry"
Given the autos collection, what MongoDB condition sets all sold fields to true? db.autos.updateMany({ price: {$gte 13500} }, { _____ })
$set: { sold: true }
What happens if the command below is used to connect to the employee database that does not yet exist? mongoose.connect("mongodb://localhost/employees")
A new database is created
Which statement is FALSE about promises?
A resolved Promise may be in a pending state.
What is missing from the age property's setter if the age property uses a private backing field? class Person { // some code omitted set age(value) { if (value >= 0) { _____; } } }
this.#age = value
Assume that using the undeclared message2 variable throws an exception. Choose ALL statements output by the code segment. function findError() { try { let message1 = "No errors"; message2; console.log(message1); } catch (error) { console.log("Error"); } finally { console.log("Finally"); } } findError(); console.log("Done");
Done Error Finally
A browser sends a POST request to a certain URL, and the server responds with a 303 status code. What would the browser do next?
Make a GET request to the URL specified by the response
Which statement is FALSE about how we developed a RESTful web API with Node?
Mocha provides the middleware to process JSON in the HTTP requests.
In class we examined Dr. McCown's solution to the LightsOutGame class. The solution had a logic error that caused the unit test below to fail. describe('newGame() method', function() { it('newGame() randomizes grid', function() { const game = new LightsOutGame(3); let currentGrid = game.gridState; game.newGame(); assert.notEqual(currentGrid, game.gridState); }); }); What did we do to get the unit test to pass?
Modified the LightsOutGame constructor to call the gridSize setter.
Assume that using the undeclared message2 variable throws an exception. What does the code segment output? function findError() { try { let message1 = "No errors here"; message2; console.log(message1); } catch (error) { console.log("There is an error"); } } findError(); console.log("Done searching");
There is an error Done searching
What is missing from the for-of loop to output all the key/value pairs in population? let population = new Map(); population.set("San Juan", 0.3); population.set("Tokyo", 9.3); for (let _____ of population) { console(city + " has population " + pop); }
[city, pop]
Which line of code displays 2 to the power of 3 in a dialog box? function power(x, y) { return new Promise(function(resolve, reject) { let answer = 1; while (y > 0) { answer *= x; y--; } resolve(answer); }); }
alert(await power(2, 3));
An Express application is stored in a variable named app, and the body-parser library has been imported to a variable named bodyParser. What code ensures the application can use parameters sent in a POST request?
app.use(bodyParser.urlencoded())
What assert method is necessary to verify that arrays nums1 and nums2 contain the same elements?
assert.deepEqual(nums1, nums2);
Refer to the pow() function and unit tests below. function pow(x, y) { let answer = x; while (y > 1) { answer *= x; y--; } return answer; } describe("pow function", function() { const testValues = [ [2, 3, 8], [1, 4, 1], [9, 0, 1] ]; for (let [x, y, answer] of testValues) { it(`${x} to power of ${y} is ${answer}`, function() { _____; }); } }); What should appear in the for-of loop's blank?
assert.equal(pow(x, y), answer)
What is missing to output the HTTP response body to the console? let url = "https://www.zybooks.com/"; let response = await fetch(url); console.log(_____);
await response.text()
What is missing to output the HTTP response body to the console? let url = "https://www.zybooks.com/";let response = await fetch(url);console.log(_____);
await response.text()
A variable declared with let in a function has _____.
block scope
Which line of code is missing so the code segment outputs "The secret ingredient is: gold flakes"? function Dessert(name) { this.name = name; let ingredient; this.setSecretIngredient = function(si) { ingredient = si; }; this.getSecretIngredient = function() { return "The secret ingredient is: " + ingredient; }; }; let chocolateMoney = new Dessert("Chocolate Money"); _____ console.log(chocolateMoney.getSecretIngredient());
chocolateMoney.setSecretIngredient("gold flakes");
Which block of code has the correct static method syntax?
class StaticExample { static methodExample() { return "this is a static method example."; } }
A _____ is a special object that maintains the set of local variables for a function and their values after the function has returned.
closure
In an interactive Node.js shell, what command is used to print the message? > _____("server accessed.")
console.log
Which of the following uses a "good practice" representation of a 'toy' model using Mongoose?
const Toy = mongoose.model("Toy", toySchema);
The Express library has been imported into a variable named express. Which of the following blocks of code creates an Express application listening on port 8080?
const app = express(); app.listen(8080);
What is missing to create a getter method? class Planet { // Some code omitted _____ { return "This is " + this.name + "."; } }
get planetName()
The variable magic is a _____. function findPower (strength, potion) { magic = strength + potion; return magic; } findPower(50, 75); console.log(magic);
global variable
If an Express server is started with the code below, what URL accesses the static file exam.html? const express = require("express"); const app = express(); app.use(express.static("test")); app.listen(2020);
http://localhost:2020/exam.html
How is the age field accessed after the following code is executed? let obj = JSON.parse('{"name":"Bobby", "age":20}');
obj.age
Examine the JavaScript data below. res.render('books.pug', { data = [ { title: 'Moby-Dick', author: 'Herman Melville' }, { title: 'The Two Towers', author: 'J.R.R. Tolkien' }, { title: 'Frankenstein', author: 'Mary Shelley' } ] }); Which Pug template correctly renders the data into an ordered list?
ol each book in data li #{book.title} by #{book.author}
Which statement changes the puppy object's name from Daisy to Darth? let puppy = { name: "Daisy", breed: "husky", color: "black" };
puppy.name = "Darth";
The Promise should be rejected if y is negative. What is missing from the if statement? function power(x, y) { return new Promise(function(resolve, reject) { if (y < 0) { _____ } ... }); }
reject(new Error("Message"));
The HTML form below is submitted. How could a middleware function access the value of the size parameter? Assume the middleware function is using the body-parser library. <form method="POST"> <input type="text" name="size"> <input type="submit" value="Go"> </form>
req.body.size
An Express app receives a request for the URL below. How could a middleware function access the value of the size parameter (i.e., "large")? /fee/fum?color=brown&size=large
req.query.size
What does stringify() return? JSON.stringify({"friends": [ {"name":"Bobby"}, {"name":"Celia"},{"name":"Judy"} ]});
single string
The express-session library manages every aspect of your session except _____.
storing the session so that the same session is available when the server restarts
The responseReceivedHandler() function is registered as the XMLHttpRequest's load event handler with response type "json". The JSON response looks like: {"title":"Rocky", "rating":"PG", "year":"1976"} What is missing from responseReceivedHandler() to display the movie year? function responseReceivedHandler() { console.log(____.year); }
this.response